Sub topic 10
Combining FILTER with GROUPING SETS and ROLLUP
Assume you know basic SELECT, WHERE, ORDER BY, aggregate functions, GROUP BY, and SQL NULL values. This chapter assumes PostgreSQL.
GROUPING SETS and ROLLUP let one query produce several grouping levels. A FILTER clause applies its condition separately at every level. This is useful for reports containing detail rows, subtotals, and a grand total.
FILTER is evaluated in every grouping set
First, give the month expression a name in a common table expression (CTE):
WITH order_rows AS (
SELECT
customer_id,
date_trunc('month', created_at) AS month,
status,
amount
FROM orders
)
SELECT
customer_id,
month,
count(*) AS orders,
count(*) FILTER (WHERE status = 'paid') AS paid_orders,
coalesce(
sum(amount) FILTER (WHERE status = 'paid'),
0
) AS paid_revenue
FROM order_rows
GROUP BY GROUPING SETS (
(customer_id, month),
(month),
()
)
ORDER BY month NULLS LAST, customer_id NULLS LAST;The three grouping sets produce:
- One row for each customer and month.
- One subtotal row for each month.
- One grand total row for all orders.
Each filtered aggregate runs within the current group. For example, paid_revenue sums only paid orders in a customer-month group, then only paid orders in a month subtotal, and finally only paid orders in the grand total.
The empty grouping set, (), means “group all input rows together.” It produces one grand-total group. coalesce changes a possible NULL result from sum to zero.
Identifying subtotal rows
A subtotal row can contain NULL in customer_id, but a real order could also have a nullable customer column in another design. Use GROUPING to identify values created by the grouping operation:
WITH order_rows AS (
SELECT
customer_id,
date_trunc('month', created_at) AS month,
status,
amount
FROM orders
)
SELECT
CASE
WHEN grouping(customer_id) = 1
AND grouping(month) = 1 THEN 'grand total'
WHEN grouping(customer_id) = 1 THEN 'month total'
ELSE 'customer detail'
END AS row_type,
customer_id,
month,
count(*) AS orders,
count(*) FILTER (WHERE status = 'refunded') AS refunded_orders
FROM order_rows
GROUP BY GROUPING SETS (
(customer_id, month),
(month),
()
)
ORDER BY month NULLS LAST, customer_id NULLS LAST;GROUPING(column) returns 1 when the column was removed for a subtotal or total. It returns 0 when the column participates in that grouping level.
ROLLUP for hierarchical totals
ROLLUP is shorthand for a particular sequence of grouping sets. This expression:
GROUP BY ROLLUP (month, customer_id)means the same as:
GROUP BY GROUPING SETS (
(month, customer_id),
(month),
()
)A complete report can therefore use ROLLUP:
WITH order_rows AS (
SELECT
customer_id,
date_trunc('month', created_at) AS month,
status,
amount
FROM orders
)
SELECT
month,
customer_id,
count(*) AS orders,
count(*) FILTER (WHERE status = 'paid') AS paid_orders,
coalesce(sum(amount) FILTER (WHERE status = 'paid'), 0) AS paid_revenue
FROM order_rows
GROUP BY ROLLUP (month, customer_id)
ORDER BY month NULLS LAST, customer_id NULLS LAST;The order of columns matters. ROLLUP (month, customer_id) creates customer totals within each month, then month totals, then a grand total. It does not automatically create a customer subtotal across all months.
Choosing GROUPING SETS or ROLLUP
Use ROLLUP when the levels form a natural hierarchy, such as year, month, and day. Use GROUPING SETS when you need unrelated combinations, such as customer-month totals plus a status total.
FILTER does not change which grouping levels exist. It changes only which rows each aggregate receives. Therefore, a filtered count or sum can appear alongside ordinary aggregates at every grouping level.
Exercise
In GROUP BY ROLLUP (month, customer_id), which grouping level represents the grand total, and how can you detect it?
Show answer
The grand total is the empty grouping set. Detect it with grouping(month) = 1 AND grouping(customer_id) = 1.