I have a table with following structure. I want to Transpose it.
BookId Status
----------------------
123A Perfect
123B Restore
123C Lost
123D Perfect
123A Perfect
123B Restore
123A Lost
123B Restore
I need the transpose table to look something like this.
Output
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
I have tried this
select
BookId,
sum('Perfect') as Perfect,
sum('Restore') as Restore
from
[dbo].[Orders]
group by
BookId
But as those are nvarchar
values, sum
is invalid. I am getting this error
I have not much hands on pivot. But tried following
select *
from
(select SellerAddress, ApplicationStatus
from [Farm_For_Books].[dbo].[Orders]) src
pivot
(sum(ApplicationStatus)
for SellerAddress in ([1], [2], [3])
) piv;