sql server - Pivot data in T-SQL -
i have group of people. lets call them a,b,c. have table shows how paid each month....
person|month|paid jan 10 feb 20 b jan 10 b feb 20 b sep 30 c jan 10 c june 20 c july 30 c sep 40
this table can , go on years , years..
is there way pivot table (nothing see needs aggregated done in pivots) in table looks following?
jan feb mar apr may jun jul agu sep 10 20 b 10 20 - - - - - - 30 c 10 - - - - 20 30 - 40
haven't run before assume common problem ideas?
if using sql server 2005 (or above), here code:
declare @cols varchar(1000) declare @sqlquery varchar(2000) select @cols = stuff(( select distinct ',' + quotename([month]) yourtable xml path('') ), 1, 1, '') set @sqlquery = 'select * (select person, month, paid yourtable ) base pivot (sum(paid) [person] in (' + @cols + ')) finalpivot' execute ( @sqlquery )
this work no matter how many different status have. dynamically assembles query pivot
. way can pivot dynamic columns assembling the query dynamically, can done in sql server.
other examples:
Comments
Post a Comment