sql - How to get column value into row header -


id amount date ------------------------------ 1 300 02-02-2010 00:00 2 400 02-02-2009 00:00 3 200 02-02-2011 00:00 4 300 22-02-2010 00:00 5 400 12-02-2009 00:00 6 500 22-02-2009 00:00 7 600 02-02-2006 00:00 8 700 02-07-2012 00:00 9 500 08-02-2012 00:00 10 800 09-02-2011 00:00 11 500 06-02-2010 00:00 12 600 01-02-2011 00:00 13 300 02-02-2019 00:00 

desired output:

 y1 y2 y3 ........... sum(amount) sum(amount) sum(amount) 

what approach, y1 year part of date, such result column following?

 2006 2009 2010 2011 2012 --------------------------------- 600 1300 800 1900 1200 

database system: sql server 2008

you need use dynamic pivot table

declare @years nvarchar(max) select @years = stuff( ( select distinct ',[' + cast(year([date]) nvarchar(4)) + ']' your_table_name_here xml path('') ), 1,1,'') declare @sql nvarchar(max) select @sql = n' select * ( select amount, year([date]) [y] your_table_name_here ) data pivot ( sum(amount) [y] in ( ' + @years + ' ) ) pivottable ' execute (@sql) 

reference: pivot docs


Comments

Popular posts from this blog

javascript - backbone.js Collection.add() doesn't `construct` (`initialize`) an object -

php - Get uncommon values from two or more arrays -

Adding duplicate array rows in Php -