WITH ROLLUP 修飾符可在 GROUP BY 結果中新增彙總行,提供多層級聚合分析,支援 OLAP(線上分析處理)操作。
假設 sales 表包含 year、country、product、profit。
-- 一般分組
SELECT year, SUM(profit) FROM sales GROUP BY year;
-- 結果:2000年 4525、2001年 3010
-- 加上 WITH ROLLUP
SELECT year, SUM(profit) FROM sales GROUP BY year WITH ROLLUP;
-- 結果:2000年 4525、2001年 3010、NULL 7535(總計行)
NULL 代表該層級的總計。
SELECT year, country, product, SUM(profit)
FROM sales
GROUP BY year, country, product WITH ROLLUP;
輸出包含四層聚合:
year + country 下的產品小計(product = NULL)year 下的國家/產品總計(country = NULL, product = NULL)year = NULL, country = NULL, product = NULL)ROLLUP 與 ORDER BY 互斥GROUP BY 列後指定 ASC/DESC 控制單欄排序報表統計、多維度資料分析、儀表板彙總展示,避免應用層二次計算總計。