开发者

PIVOT basics: Why do my aggregate return NULL?

开发者 https://www.devze.com 2023-01-25 03:29 出处:网络
I\'ve got a basic PIVOT-question here that probably won\'t cause you gurus any trouble: Ive got this SQL that is working fine:

I've got a basic PIVOT-question here that probably won't cause you gurus any trouble:

Ive got this SQL that is working fine:

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

This returns sonething like:

2010 7000000
2007 8051222
2008 7099057
2009 13088790

Now I want to pivot the table usi开发者_高级运维ng the same principles as described in this MSDN-article: http://msdn.microsoft.com/en-us/library/ms177410.aspx

I tried this:

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;

But this returns a bunch of NULLs! :(

Amount NULL NULL NULL NULL NULL

What am I doing wrong? Any help appreciated!

Thanks!


Thank you Barry. I misread the documentation on MSDN, and thought the [0], [1] etc labels where enumerations of the pivot-columns... (!)

Replacing them with the actual Years made the aggregations work!

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; 
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号