sql >> Base de Datos >  >> RDS >> Sqlserver

Pivotar una tabla junto con la suma del valor de la columna cuando el tipo de columna es nvarchar

conditional aggregation podría usarse

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

Demostración de Rextester