Pivoting a table along with sum of column value when column type is nvarchar

前端 未结 1 1755
栀梦
栀梦 2021-01-21 04:06

I have a table with following structure. I want to Transpose it.

 BookId    Status   
 ----------------------
 123A      Perfect
 123B      Restore
 123C      Lo         


        
1条回答
  •  借酒劲吻你
    2021-01-21 04:16

    conditional aggregation might be used

    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

    0 讨论(0)
提交回复
热议问题