跳至主要内容

Comparing GROUP BY / ROLLUP / GROUPING SETS / CUBE in SQL

In Microsoft SQL Server / Azure SQL / Fabric Warehouse, these three operators are extensions of GROUP BY.

Their purpose: Calculate subtotals and grand totals in one query, without writing multiple UNIONs.


Sample Data​

OrderYearProductNameQty
2023A10
2023B20
2024A15
2024B25

1) GROUP BY (Standard Baseline)​

SELECT OrderYear, ProductName, SUM(Qty) AS TotalQty
FROM Sales
GROUP BY OrderYear, ProductName;

Result:

OrderYearProductNameTotalQty
2023A10
2023B20
2024A15
2024B25

This is standard GROUP BY with no subtotals.


2) ROLLUP(OrderYear, ProductName)​

SELECT OrderYear, ProductName, SUM(Qty) AS TotalQty
FROM Sales
GROUP BY ROLLUP(OrderYear, ProductName);

Result:

OrderYearProductNameTotalQty
2023A10
2023B20
2023NULL30 ← 2023 subtotal
2024A15
2024B25
2024NULL40 ← 2024 subtotal
NULLNULL70 ← grand total

ROLLUP = Year subtotals + grand total for all columns


3) GROUPING SETS​

SELECT OrderYear, ProductName, SUM(Qty) AS TotalQty
FROM Sales
GROUP BY GROUPING SETS
(
(OrderYear, ProductName), -- Detail level
(OrderYear), -- Year subtotals
(ProductName) -- Product subtotals
);

Result:

OrderYearProductNameTotalQty
2023A10
2023B20
2023NULL30
2024A15
2024B25
2024NULL40
NULLA25 ← Product A total
NULLB45 ← Product B total

GROUPING SETS = Choose which subtotals you want No mandatory grand total


4) CUBE(OrderYear, ProductName)​

SELECT OrderYear, ProductName, SUM(Qty) AS TotalQty
FROM Sales
GROUP BY CUBE(OrderYear, ProductName);

Result:

OrderYearProductNameTotalQty
2023A10
2023B20
2023NULL30
2024A15
2024B25
2024NULL40
NULLA25
NULLB45
NULLNULL70 ← grand total

CUBE = All possible combinations = GROUPING SETS(detail + year subtotals + product subtotals + grand total)


Quick Summary​

OperatorDescription
ROLLUPHierarchical subtotals from left to right
GROUPING SETSChoose specific subtotal combinations you want
CUBEAll possible combinations - complete subtotals