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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With