我遇到了一个非常意外的错误,我不确定这是由于兼容性设置还是愚蠢的。 (我正在使用SQL Server 2008 R2。)我的查询在数据透视表内的聚合上失败。
段:
select * from @sales
pivot
(
sum(Amount)
for Quarter
in (Q1, Q2, Q3, Q4)
) as p
sum(Amount)
答案 0 :(得分:1)
适用于我的表格定义
declare @sales table
(
[Year] int,
Quarter char(2),
Amount float
)
所以可能是兼容性问题。你可以做到
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]
对于可在SQL Server 2000兼容模式下运行的解决方案。