如何将列值导入行标题

时间:2012-07-07 09:04:11

标签: sql

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

期望的输出:

   Y1          Y2            Y3 ...........
 sum(amount)   sum(amount)   sum(amount)

什么是方法,其中Y1是日期的年份部分,以便结果列如下?

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

数据库系统:SQL Server 2008

1 个答案:

答案 0 :(得分:0)

您需要使用dynamic PIVOT Table

DECLARE @Years nvarchar(max)
SELECT @Years =
  STUFF(
  (
    select distinct ',[' + cast(Year([date]) as nvarchar(4)) + ']'
    from YOUR_TABLE_NAME_HERE
    for xml path('')
  ),
  1,1,'')

DECLARE @SQL nvarchar(max)
SELECT @SQL = N'
select
  *
from (
  select
    amount, year([date]) as [y]
  from YOUR_TABLE_NAME_HERE
) Data
PIVOT (
  sum(amount)
  FOR [y]
  IN (
    ' + @Years + '
  )
) PivotTable
'

EXECUTE (@SQL)

参考:PIVOT Docs