Sqlserver
 sql >> Datenbank >  >> RDS >> Sqlserver

Pivotieren einer Tabelle zusammen mit der Summe des Spaltenwerts, wenn der Spaltentyp nvarchar ist

conditional aggregation verwendet werden

with Orders( BookId, Status ) as
(
 select '123A','Perfect' union all
 select '123B','Restore' union all
 select '123C','Lost'    union all
 select '123D','Perfect' union all
 select '123A','Perfect' union all
 select '123B','Restore' union all
 select '123A','Lost'    union all
 select '123B','Restore'   
)    
select
    BookId,
    sum(1) as [Total],
    sum(case when Status='Perfect' then 1 else 0 end ) as [Perfect],
    sum(case when Status='Restore' then 1 else 0 end ) as [Restore],
    sum(case when Status='Lost' then 1 else 0 end ) as [Lost]    
from 
    [Orders]
group by BookId;

BookId  Total   Perfect Restore Lost
123A      3        2       0     1
123B      3        0       3     0
123C      1        0       0     1
123D      1        1       0     0

Rextester-Demo