需求:按月份統計 2014、2015 年總金額,輸出格式:Month | 2014 | 2015。
Statistics
- Month (int)
- Year (int) -- 2014, 2015
- TotalPrice (decimal)
SELECT
Month,
SUM(CASE WHEN Year = 2014 THEN TotalPrice ELSE 0 END) AS Total_2014,
SUM(CASE WHEN Year = 2015 THEN TotalPrice ELSE 0 END) AS Total_2015
FROM Statistics
GROUP BY Month
ORDER BY Month;
CASE WHEN Year = 2014 THEN TotalPrice ELSE 0 END:將 2014 年金額保留,其他年份置 0。SUM(...):按月份分組後求和,自動過濾掉 0 值,得到該月 2014 總額。GROUP BY Month:按月份聚合。SELECT Month,
SUM(CASE WHEN Year = 2014 THEN TotalPrice END) AS `2014`,
SUM(CASE WHEN Year = 2015 THEN TotalPrice END) AS `2015`
FROM Statistics
GROUP BY Month;
-- ELSE 0 可省略,SUM 忽略 NULL
SELECT Month, [2014], [2015]
FROM (
SELECT Month, Year, TotalPrice FROM Statistics
) src
PIVOT (
SUM(TotalPrice) FOR Year IN ([2014], [2015])
) pvt
ORDER BY Month;
Month | 2014 | 2015
1 | 12500.00 | 15800.00
2 | 9800.00 | 11200.00
...
12 | 18600.00 | 20100.00
CASE WHEN + SUM 兼容性最強,無需 PIVOT 語法支援,推薦通用方案。