SQL ROLLUP clause
Adds a subtotal row for each grouping prefix plus a grand-total row.
- Returns
detail rows plus subtotals- In this category
- 39 of 52
語法
GROUP BY ROLLUP(a, b) | GROUP BY a, b WITH ROLLUP
引擎支援
| 引擎 | Support | 備註 |
|---|---|---|
| SQL Server | 是 | Supported under this name. |
| PostgreSQL | 是 | Supported under this name. |
| MySQL | 是 | syntax differs: GROUP BY a, b WITH ROLLUP |
| SQLite | Not built in | no ROLLUP; emulate with UNION ALL of grouped queries |
| Oracle | 是 | Supported under this name. |
範例
PostgreSQL
SELECT region, city, SUM(amount) FROM sales GROUP BY ROLLUP(region, city);
MySQL
SELECT region, city, SUM(amount) FROM sales GROUP BY region, city WITH ROLLUP;
小知識
- ROLLUP(a, b) produces (a, b), (a) and () levels: a hierarchy, not every combination; that is CUBE.
- Subtotal rows show NULL for the rolled-up columns, colliding with real NULLs unless you add GROUPING().
- MySQL's WITH ROLLUP is the same idea in a different position. Before 8.0.12 it could not be combined with ORDER BY; current versions allow it, and ORDER BY a puts the NULL subtotal rows first.
Questions about ROLLUP
Which row is the grand total?
The one with NULL in every rolled-up column; confirm with GROUPING(region) = 1.
What is MySQL's syntax?
GROUP BY a, b WITH ROLLUP instead of GROUP BY ROLLUP(a, b).
ROLLUP vs CUBE?
ROLLUP rolls up along the listed order only; CUBE computes every subset of the columns.
Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.
Related on SQLly
- Cross-tab with row and column totals Snippet
- SQL aggregation & HAVING interview questions Interview questions
Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, Oracle.
Functions your engine actually has
SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.