SQL Server 2005 的 GROUP BY WITH CUBE/ROLLUP 雖支援多維彙總,但產生的組合固定(全維度交叉或層級向上彙總),無法自訂「只要這幾組維度組合」。
SELECT ProductKey, OrderDateKey, CustomerKey, PromotionKey,
SUM(UnitPrice) AS SumUnitPrice,
SUM(OrderQuantity) AS SumOrderQuantity
FROM dbo.FactInternetSales
GROUP BY GROUPING SETS (
(ProductKey, OrderDateKey, CustomerKey, PromotionKey), -- 明細層
(ProductKey, OrderDateKey, CustomerKey), -- 少一維
() -- 總計
);
未出現在某 GROUPING SET 中的欄位,結果集自動填充 NULL。
傳統寫法需 UNION ALL 多次掃描:
SELECT ..., 'Detail' AS Level FROM ... GROUP BY ProductKey, OrderDateKey, CustomerKey, PromotionKey
UNION ALL
SELECT ..., 'SubTotal' FROM ... GROUP BY ProductKey, OrderDateKey, CustomerKey
UNION ALL
SELECT ..., 'GrandTotal' FROM ... GROUP BY ();
GROUPING SETS 單次掃描完成所有彙總,I/O 與 CPU 成本大幅降低。
GROUP BY GROUPING SETS (
ROLLUP (ProductKey, OrderDateKey), -- 階層向上
CUBE (CustomerKey, PromotionKey), -- 全交叉
() -- 總計
);
GROUPING(col):該欄位是否為彙總產生的 NULL(1=是,0=否)GROUPING_ID(col1, col2...):多欄位組合位圖,便於區分彙總層級SELECT CASE WHEN GROUPING(ProductKey)=1 THEN 'All Products' ELSE ProductKey END AS Product,
SUM(UnitPrice)
FROM ...
GROUP BY GROUPING SETS ((ProductKey), ())
ORDER BY GROUPING_ID(ProductKey);
GROUPING SETS 將「彙總組合自定義」與「單次掃描高效執行」完美結合,是 SQL Server 2008+ 進行多維分析的首選語法。配合 GROUPING_ID 可輕鬆構建階層報表導航。