Prova cosi (ho copiato le 18 righe che hai postato). La mia tabella si chiama toto (cioè pippo in Francese
)
Forse ci sono altri metodi ma un paio di ore fa erano 15 anni che non usavo sql server.
codice:
with a (az,mat,row_) as (
SELECT azienda, matricola, ROW_NUMBER() OVER (ORDER BY azienda) as row_ FROM toto
),
b (az, amin, amax) as (
select az, min(row_) as amin, max(row_) as amax from a group by az
),
c (az, amin, amax, mat) as (
select a.az, amin, amax, mat from b, a
where a.row_ between amin and amax
),
d (az, mat, pos) as (
select c.az, c.mat, row_ - amin + 1 as pos from c,a
where c.az = a.az and c.mat = a.mat
),
primo (az, mat1) as (select az, mat from d where pos = 1),
secondo (az, mat2) as (select az, mat from d where pos = 2),
terzo (az, mat3) as (select az, mat from d where pos = 3),
quarto (az, mat4) as (select az, mat from d where pos = 4),
quinto (az, mat5) as (select az, mat from d where pos = 5)
select primo.az, mat1, mat2, mat3, mat4, mat5 from primo
left join secondo on secondo.az = primo.az
left join terzo on terzo.az = secondo.az
left join quarto on quarto.az = terzo.az
left join quinto on quinto.az = quarto.az
Dà
codice:
az mat1 mat2 mat3 mat4 mat5
0101233 IT007000001249 IT007020001525 NULL NULL NULL
0101417 IT007000001810 IT007000004786 NULL NULL NULL
0119647 IT007000004119 IT007000004787 IT007020004080 NULL NULL
0223021 IT018005100754 IT013000453456 IT018005100776 NULL NULL
0921434 IT018000000303 IT018000000299 IT018000002436 IT016000049815 IT012000022684
0930405 IT017004901212 IT017004901213 IT017004901202 NULL NULL