// aggregates reference

SQL GROUP BY CUBE

CUBE(region, product) groups by (region, product), (region), (product) and () in one query: the detail rows, both sets of subtotals and the grand total.

Kategorie
Aggregates
Returns
extra subtotal rows with NULL in the rolled-up columns
In this category
49 of 52

Syntax

GROUP BY CUBE(col1, col2 [, ...])

Engine-Unterstützung

EngineSupportNotizen
SQL Server Ja CUBE(...), also the older WITH CUBE
PostgreSQL Ja Supported under this name.
MySQL Not built in CUBE fails with 'CUBE' is not supported; WITH ROLLUP only
SQLite Not built in no CUBE or ROLLUP; UNION ALL the groupings
Oracle Ja Supported under this name.

Beispiele

PostgreSQL

SELECT region, product, SUM(n) AS total
FROM (VALUES ('E', 'x', 1), ('E', 'y', 2), ('W', 'x', 3)) AS t(region, product, n)
GROUP BY CUBE(region, product)
ORDER BY region NULLS LAST, product NULLS LAST;  -- 8 rows: 3 detail, 2 region totals, 2 product totals, 1 grand total

SQL Server

SELECT region, product, SUM(n) AS total, GROUPING(region) AS g_region, GROUPING(product) AS g_product
FROM (VALUES ('E', 'x', 1), ('E', 'y', 2), ('W', 'x', 3)) AS t(region, product, n)
GROUP BY CUBE(region, product);

Oracle

SELECT region, product, SUM(n) AS total
FROM (SELECT 'E' AS region, 'x' AS product, 1 AS n FROM dual
      UNION ALL SELECT 'E', 'y', 2 FROM dual
      UNION ALL SELECT 'W', 'x', 3 FROM dual)
GROUP BY CUBE(region, product)
ORDER BY region, product;

Gut zu wissen

  • n columns produce 2^n groupings: CUBE over four columns is sixteen GROUP BYs in one pass, and the row count grows fast.
  • Subtotal rows show NULL in the rolled-up columns. GROUPING(col) returns 1 on those rows, which tells them apart from real NULL values.
  • CUBE implies no sort order. Add ORDER BY, often on GROUPING(col), to put the totals where readers expect them.

Questions about CUBE

CUBE or ROLLUP?

ROLLUP(a, b) follows a hierarchy: (a, b), (a), (). CUBE(a, b) also adds (b) on its own. Use ROLLUP for year > month style drill-downs and CUBE for cross-tab totals.

How do I get CUBE results in MySQL?

Combine queries: GROUP BY a, b WITH ROLLUP gives (a, b), (a) and (); UNION ALL a GROUP BY b query adds the missing (b) subtotals.

Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.

Cheat sheets for the engines that have it: SQL Server, PostgreSQL, Oracle.

// fewer lookups

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.