liveBook · Manning

Grouping set

As explained in DuckDB in Action

A grouping set is a specified combination of grouping keys for which a grouped aggregate result is computed.

A grouping set specifies one combination of grouping keys for which SQL computes aggregates. Combining several sets produces a drill-down report at multiple detail levels in one query. section 4.4

Power-production totals at three levels

A readings report can combine system-and-year totals, year totals, and an overall total: SELECT year(read_on) AS year, system_id, count(*), round(sum(power) / 4 / 1000, 2) AS kWh FROM readings GROUP BY GROUPING SETS ((year, system_id), year, ()) ORDER BY year NULLS FIRST, system_id NULLS FIRST; The empty grouping set () creates the overall row. Keys omitted from a set appear as NULL, so year-only rows have NULL system_id. section 4.4

Related shorthand expresses common grouping-set patterns:

  • ROLLUP(year, system_id) generates hierarchical sets: (year, system_id), (year), and (). section 4.4
  • CUBE(year, system_id) generates combinations: (year, system_id), (year), (system_id), and (). section 4.4
Listing 4.12 Explicitly using GROUPING SETS
SELECT year(read_on) AS year,
       system_id,
       count(*),
       round(sum(power) / 4 / 1000, 2) AS kWh
FROM readings
GROUP BY GROUPING SETS ((year, system_id), year, ())
ORDER BY year NULLS FIRST, system_id NULLS FIRST;

Inspect the runnable SQL that produces the multi-level readings report. section 4.4

How DuckDB in Action covers it

How deep it goes
Explains explicit sets, NULL subtotal keys, and ROLLUP and CUBE shorthand through a worked readings query.
Examples
Uses readings grouped by year and system_id to calculate counts, power totals, yearly subtotals, and an overall total.
What it assumes
Builds on GROUP BY and aggregate queries, then extends them to multiple grouping-key combinations.
What you can do after
Apply it via SQL to replace multiple aggregation queries with one multi-level report.
How it connects
Connects GROUPING SETS with GROUP BY, aggregate functions, ROLLUP, and CUBE.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of DuckDB in Action. The section links point to the parts of the book it draws on.