Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL PIVOT Syntax Error on Aggregate

I'm getting a very unexpected error, and I'm not sure if it is due to compatibility settings or something silly. (I'm using SQL Server 2008 R2.) My query fails on the aggregate inside the pivot.

Here is the full sample code.

Snippet:

select * from @sales
pivot
(
  sum(Amount)
  for Quarter
  in (Q1, Q2, Q3, Q4)
) as p

Incorrent syntax on the line sum(Amount)

like image 799
Peet Brits Avatar asked Sep 14 '26 02:09

Peet Brits


1 Answers

Works for me for table definition

declare @sales table
(
 [Year] int,
 Quarter char(2),
 Amount float
)

so presumably it is a compatibility level issue. You can do

SELECT 
    [Year],
    SUM(CASE WHEN Quarter = 'Q1' THEN Amount END) AS Q1,
    SUM(CASE WHEN Quarter = 'Q2' THEN Amount END) AS Q2,
    SUM(CASE WHEN Quarter = 'Q3' THEN Amount END) AS Q3,
    SUM(CASE WHEN Quarter = 'Q4' THEN Amount END) AS Q4
from @sales   
group by [Year]

For a solution that will work under SQL Server 2000 compatibility mode.

like image 102
Martin Smith Avatar answered Sep 15 '26 20:09

Martin Smith



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!