sql server 2008 - SQL query to output multiple columns based on the value of 1 column -
i have been banging head against wall @ few hours. have managed data need down 1 table, can not figure out how write select statement output way want.
basically have table:
id| date | cost 03/11 5 02/11 4 b 01/11 3 b 04/11 7
the column changes query column output date column. able group id's together, each row containing id , cost of each item per month pertains id, or null if there no items month (from jan-dec)
output of query:
id| jan |feb | march | apr | may | jun | jul |......| oct | nov | dec null 4 5 null null.................................null b 3 null null 7 null.................................null
any in right direction appreciated!
thank you.
;with data(id, date, cost) ( select 'a', '20110311', 5 union select 'a', '20110211', 4 union select 'b', '20110111', 3 union select 'b', '20110411', 7 ) --- above creates virtual dataset named data. --- query starts below here select * ( select id, left(upper(datename(month,date)),3) month_, cost data ) p pivot (sum(cost) month_ in ([jan],[feb],[mar],[apr],[may],[jun],[jul],[aug],[sep],[oct],[nov],[dec])) v
Comments
Post a Comment