PIVOT基础知识:为什么我的聚合返回NULL?

时间:2010-11-16 14:46:59

标签: sql windows-server-2008 pivot

我在这里有一个基本的PIVOT问题,可能不会给你的大师带来任何麻烦:

我得到了这个正常运行的SQL:

SELECT order_year, SUM(amount) AS Amount 
FROM dbo.mytable
GROUP BY order_year;

这会返回声音:

2010 7000000
2007 8051222
2008 7099057
2009 13088790

现在我想使用与此MSDN文章中描述的相同原则来转动表:http://msdn.microsoft.com/en-us/library/ms177410.aspx

我试过了:

SELECT 'Amount' AS Total_Amount_Sorted_By_Order_Year, 
[0], [1], [2], [3], [4]
FROM
(SELECT order_year, amount 
    FROM dbo.mytable ) AS SourceTable
PIVOT
(
SUM(amount)
FOR order_year IN ([0], [1], [2], [3], [4])
) AS PivotTable;

但这会返回一堆NULL! :(

Amount NULL NULL NULL NULL NULL

我做错了什么?任何帮助表示赞赏!

谢谢!

1 个答案:

答案 0 :(得分:3)

谢谢巴里。我误读了MSDN上的文档,并认为[0],[1]等标签中的pivot-columns的枚举...(!)

用实际年份取代它们使聚合工作正常!

SELECT 'Amount' AS Total_Amount_Sorted_By_Order_Year,  
[2007], [2008], [2009], [2010]
FROM 
(SELECT order_year, amount  
    FROM dbo.mytable ) AS SourceTable 
PIVOT 
( 
SUM(amount) 
FOR order_year IN ([2007], [2008], [2009], [2010]) 
) AS PivotTable;