SQL Server dynamic PIVOT query? -


i've been tasked coming means of translating following data:

date        category        amount 1/1/2012    abc             1000.00 2/1/2012    def             500.00 2/1/2012    ghi             800.00 2/10/2012   def             700.00 3/1/2012    abc             1100.00 

into following:

date        abc             def             ghi 1/1/2012    1000.00 2/1/2012                    500.00 2/1/2012                                    800.00 2/10/2012                   700.00 3/1/2012    1100.00 

the blank spots can nulls or blanks, either fine, , categories need dynamic. possible caveat we'll running query in limited capacity, means temp tables out. i've tried research , have landed on pivot i've never used before don't understand it, despite best efforts figure out. can point me in right direction?

dynamic sql pivot:

create table temp (     date datetime,     category varchar(3),     amount money )  insert temp values ('1/1/2012', 'abc', 1000.00) insert temp values ('2/1/2012', 'def', 500.00) insert temp values ('2/1/2012', 'ghi', 800.00) insert temp values ('2/10/2012', 'def', 700.00) insert temp values ('3/1/2012', 'abc', 1100.00)   declare @cols nvarchar(max),     @query  nvarchar(max);  set @cols = stuff((select distinct ',' + quotename(c.category)              temp c             xml path(''), type             ).value('.', 'nvarchar(max)')          ,1,1,'')  set @query = 'select date, ' + @cols + '              (                 select date                     , amount                     , category                 temp            ) x             pivot              (                  max(amount)                 category in (' + @cols + ')             ) p '   execute(@query)  drop table temp 

results:

date                        abc         def    ghi 2012-01-01 00:00:00.000     1000.00     null    null 2012-02-01 00:00:00.000     null        500.00  800.00 2012-02-10 00:00:00.000     null        700.00  null 2012-03-01 00:00:00.000     1100.00     null    null 

Comments

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

javascript - Get parameter of GET request -

javascript - Twitter Bootstrap - how to add some more margin between tooltip popup and element -