Sqlserver
 sql >> Database >  >> RDS >> Sqlserver

Pivot di colonne multiple in T-SQL

Riscrivi usando MAX(CASE...) e GROUP BY:

select 
  field1
, [1] = max(case when RowID = 1 then field2 end)
, [2] = max(case when RowID = 2 then field2 end)
, [3] = max(case when RowID = 3 then field2 end)
, [4] = max(case when RowID = 4 then field2 end)
from (
  select 
    field1
  , field2
  , RowID = row_number() over (partition by field1 order by field2)
  from tblname
  ) SourceTable
group by 
  field1

Da lì puoi aggiungere campo 3, campo 4, ecc.