Video in progress

How do you produce subtotals and grand totals (`ROLLUP`, `GROUPING SETS`) in one query for a report?

GROUP BY ROLLUP (region, city) gives the per-city, per-region and grand totals in one query. GROUPING SETS lets you state exactly which combinations you need. The GROUPING() function tells which row is a total.

📖 Answer

The simple way is three queries and a UNION ALL. That reads the table three times. With ROLLUP it's one:

SELECT region,
       city,
       sum(total) AS revenue,
       GROUPING(region, city) AS lvl
FROM orders
GROUP BY ROLLUP (region, city)
ORDER BY region NULLS LAST, city NULLS LAST;
region city revenue lvl
Toshkent Chilonzor 500 0
Toshkent Yunusobod 300 0
Toshkent NULL 800 1
NULL NULL 1200 3

lvl is a bitmask: if a column is "rolled up", its bit is 1. This matters because city can also be NULL in the data itself, and without GROUPING() you'd confuse a "city not specified" row with a "region total".

Other variants:

GROUP BY CUBE (region, channel)                    -- all combinations
GROUP BY GROUPING SETS ((region), (channel), ())   -- only the ones you need

On the Java side, when I read such a result into a DTO, I mark the row as a "total" based on lvl, so the UI can show it in bold.