表结构如下
value date
100 2000/2/5
123 2000/5/6
3213 2003/5/8
要求一句sql实现按年度统计各季度总量和年度总量
年度 1季度值 2季度值 3季度值 4季度值 年度值
2000 100 123 null null 223
2003 null 3213 null null 3213
答案
SELECT year([date]) AS 年份, SUM(CASE WHEN (month([date]) + 2)
/ 3 = 1 THEN [value] ELSE 0 END) AS [1季度值], SUM(CASE WHEN
(month([date]) + 2)
/ 3 = 2 THEN [value] ELSE 0 END) AS [2季度值], SUM(CASE WHEN
(month([date]) + 2)
/ 3 = 3 THEN [value] ELSE 0 END) AS [3季度值], SUM(CASE WHEN
(month([date]) + 2)
/ 3 = 4 THEN [value] ELSE 0 END) AS [4季度值], SUM([value]) AS 年度值
FROM test
GROUP BY year([date])