// aggregates reference

SQL GROUPING function

Returns 1 when the column is a rolled-up placeholder NULL, 0 when it is a real value.

Категория
Aggregates
Returns
integer
In this category
36 of 52

Синтаксис

GROUPING(col) | GROUPING(col1, col2)

Поддержка движка

ДвижокSupportЗаметки
SQL Server Да Supported under this name.
PostgreSQL Да Supported under this name.
MySQL Да MySQL 8.0+, with WITH ROLLUP only
SQLite Not built in no ROLLUP, so nothing to flag
Oracle Да one argument; GROUPING_ID for several

Примеры

PostgreSQL

SELECT make, GROUPING(make), SUM(sales) FROM items_sold GROUP BY ROLLUP(make);

SQL Server

SELECT make, GROUPING(make), SUM(sales) FROM items_sold GROUP BY make WITH ROLLUP;

Полезно знать

  • Without ROLLUP, CUBE or GROUPING SETS in the query, GROUPING is always 0.
  • PostgreSQL and MySQL accept several columns and return a bitmask (rightmost argument = lowest bit); SQL Server and Oracle take exactly one and offer GROUPING_ID for the bitmask.
  • It is the only reliable way to tell a real NULL value from the NULL that ROLLUP prints on subtotal rows.

Questions about GROUPING

What do 0 and 1 mean?

0 = the column holds a real value; 1 = the row is a super-aggregate and the column shows a placeholder NULL.

Can I filter subtotal rows?

Yes: HAVING GROUPING(make) = 1 keeps only the rolled-up rows; = 0 keeps only detail rows.

Does it work without ROLLUP?

It runs, but every row returns 0.

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

// 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.