Multi-Level Reports, Pivots and Result-Set Comparisons
A PostgreSQL 17 lab: build subtotals and grand totals with ROLLUP and GROUPING SETS, label them with GROUPING(), pivot months into columns with FILTER, unpivot them again with LATERAL, take the top N per group, and prove two report queries agree with EXCEPT and INTERSECT.
Contentsand lesson path
On this page
- Goal and setup
- Step 1: Load the sales table
- Step 2: Subtotals and a grand total with ROLLUP
- Step 3: Choose your own levels with GROUPING SETS, or all of them with CUBE
- Step 4: Pivot months into columns, then unpivot them
- Step 5: The top two cities per region with LATERAL
- Step 6: Prove that a rewritten report returns the same rows
- Check your understanding
- Apply it
- Review prompt
Lessons of Advanced SQL
- Window Functions: Partitions, Order and Frames Concept · 25 min
- Lab: Retention, Running Totals and Gaps-and-Islands Lab · 30 min
- Readable Step-by-Step Queries with CTEs and Recursion Worked example · 25 min
- Multi-Level Reports, Pivots and Result-Set Comparisons Lab · 25 min
- Deduplicate, MERGE and Package the Load as a Procedure Lab · 30 min
- Check: Analytical Query Challenge Knowledge check · 8 questions
What you will learn
- Produce multi-level summaries with GROUPING SETS or ROLLUP, pivot rows into columns (and back) with conditional aggregation or LATERAL, and compare result sets with UNION, INTERSECT and EXCEPT.
Prerequisites: SQL Fundamentals
01. Goal and setup
Finance reports rarely stop at one level. A typical sheet shows revenue per city, a subtotal per region and a grand total, and another shows categories as rows and months as columns. You can build these with several queries glued together by UNION ALL, but SQL has dedicated tools that do it in one pass and label each level. In this lab you use them on a small sales table, and then you do something every data engineer needs before replacing a report: prove that the new query returns exactly the same rows as the old one.
You need Docker and the sql-lab container from the window functions lab (PostgreSQL 17; tested with 17.11). Work in a folder report-lab/.
report-lab/
├── seed.sql step 1: the sales table
├── rollup.sql step 2: subtotals with ROLLUP and GROUPING()
├── sets.sql step 3: GROUPING SETS and CUBE
├── pivot.sql step 4: pivot and unpivot
├── topn.sql step 5: top two cities per region with LATERAL
└── compare.sql step 6: compare an old and a new report02. Step 1: Load the sales table
Each row is one month of sales for a city and a product category. Sale 6 has no city, because the shop that made it did not record one. That NULL is deliberate: it will look exactly like a subtotal in step 2. If the container is stopped, run docker start sql-lab first.
CREATE TABLE sales (
sale_id int PRIMARY KEY,
region text NOT NULL,
city text, -- NULL when the shop did not record a city
category text NOT NULL,
month date NOT NULL,
amount numeric(8,2) NOT NULL
);
INSERT INTO sales VALUES
( 1, 'north', 'Leeds', 'books', '2026-01-01', 100),
( 2, 'north', 'Leeds', 'games', '2026-01-01', 50),
( 3, 'north', 'Leeds', 'books', '2026-02-01', 120),
( 4, 'north', 'York', 'books', '2026-01-01', 70),
( 5, 'north', 'York', 'games', '2026-02-01', 30),
( 6, 'north', NULL, 'games', '2026-02-01', 20),
( 7, 'north', 'Hull', 'books', '2026-01-01', 10),
( 8, 'south', 'Bath', 'books', '2026-01-01', 90),
( 9, 'south', 'Bath', 'games', '2026-02-01', 60),
(10, 'south', 'Exeter', 'books', '2026-02-01', 40),
(11, 'south', 'Exeter', 'games', '2026-01-01', 80);
SELECT count(*) AS sales, sum(amount) AS total FROM sales;docker exec sql-lab psql -U postgres -X -q -c "SET client_min_messages = warning" \
-c "DROP DATABASE IF EXISTS reports" -c "CREATE DATABASE reports"
docker exec -i sql-lab psql -U postgres -d reports -X -q < seed.sql sales | total
-------+--------
11 | 670.00
(1 row)03. Step 2: Subtotals and a grand total with ROLLUP
A grouping set is one list of columns to group by. GROUP BY ROLLUP (region, city) is shorthand for three grouping sets computed in one pass: (region, city) for the detail rows, (region) for a subtotal per region, and () for the grand total. ROLLUP removes columns from the right, one at a time, so the order you write them in is the hierarchy, from the top level down. In a subtotal row the grouped-away columns are NULL.
That creates a problem when the data itself contains NULL. The first query below prints north twice with an empty city. The second query fixes this with grouping(). grouping(col) returns 1 when col was grouped away in that row and 0 when it is a real value, even a real NULL. With several arguments it returns a bit mask, so grouping(region, city) is 0 for detail rows, 1 for region subtotals and 3 for the grand total.
SELECT region, city, sum(amount) AS revenue
FROM sales
GROUP BY ROLLUP (region, city)
ORDER BY region, city, revenue DESC;
SELECT CASE WHEN grouping(region) = 1 THEN 'ALL' ELSE region END AS region,
CASE WHEN grouping(region, city) = 1 THEN 'subtotal'
WHEN grouping(region, city) = 3 THEN 'grand total'
ELSE coalesce(city, '(unknown)') END AS city,
grouping(region, city) AS level,
sum(amount) AS revenue
FROM sales
GROUP BY ROLLUP (region, city)
ORDER BY grouping(region), region, grouping(city), city;docker exec -i sql-lab psql -U postgres -d reports -X -q < rollup.sql region | city | revenue
--------+--------+---------
north | Hull | 10.00
north | Leeds | 270.00
north | York | 100.00
north | | 400.00
north | | 20.00
south | Bath | 150.00
south | Exeter | 120.00
south | | 270.00
| | 670.00
(9 rows)
region | city | level | revenue
--------+-------------+-------+---------
north | (unknown) | 0 | 20.00
north | Hull | 0 | 10.00
north | Leeds | 0 | 270.00
north | York | 0 | 100.00
north | subtotal | 1 | 400.00
south | Bath | 0 | 150.00
south | Exeter | 0 | 120.00
south | subtotal | 1 | 270.00
ALL | grand total | 3 | 670.00
(9 rows)In the first result you cannot tell the north subtotal (400) from the sale without a city (20). In the second, the unknown city has level 0, the subtotal level 1, and the grand total level 3. Sorting by grouping(...) puts each subtotal under its detail rows. Check the numbers: north is 270 + 100 + 10 + 20 = 400, south is 150 + 120 = 270, and the grand total, 670, matches step 1.
04. Step 3: Choose your own levels with GROUPING SETS, or all of them with CUBE
GROUPING SETS lists exactly the sets you want, which need not form a hierarchy. Below, one query returns revenue per region, revenue per category and the grand total, which is three separate GROUP BY queries in one statement. CUBE (a, b) produces every combination: (a, b), (a), (b) and (). The second query counts the rows that ROLLUP and CUBE produce over region and category, to show how fast CUBE grows: with n columns it computes 2ⁿ grouping sets.
SELECT region, category, sum(amount) AS revenue
FROM sales
GROUP BY GROUPING SETS ((region), (category), ())
ORDER BY region NULLS LAST, category NULLS LAST;
SELECT 'rollup' AS kind, count(*) AS result_rows
FROM (SELECT 1 FROM sales GROUP BY ROLLUP (region, category)) r
UNION ALL
SELECT 'cube', count(*)
FROM (SELECT 1 FROM sales GROUP BY CUBE (region, category)) c;docker exec -i sql-lab psql -U postgres -d reports -X -q < sets.sql region | category | revenue
--------+----------+---------
north | | 400.00
south | | 270.00
| books | 430.00
| games | 240.00
| | 670.00
(5 rows)
kind | result_rows
--------+-------------
rollup | 7
cube | 9
(2 rows)ROLLUP gives 4 detail rows (2 regions × 2 categories), 2 region subtotals and 1 grand total: 7. CUBE adds 2 category subtotals: 9. Use CUBE when people really slice in every direction, and GROUPING SETS when you know which levels the report needs, because every extra set is extra work and extra rows to explain.
05. Step 4: Pivot months into columns, then unpivot them
To pivot is to turn values of one column (here, months) into separate columns. PostgreSQL has no PIVOT keyword, so you use conditional aggregation: one aggregate per output column, each counting only its own rows. sum(amount) FILTER (WHERE month = ...) does exactly that, and is easier to read than the older sum(CASE WHEN ... THEN amount END), which gives the same result. The column list is fixed when you write the query: a new month needs a new line, or a generated query. (The tablefunc extension offers crosstab(), which also needs the output columns declared.)
To unpivot, turn columns back into rows. A LATERAL subquery may refer to columns of the row to its left in the FROM list, so CROSS JOIN LATERAL (VALUES (...), (...)) builds a small table from each pivoted row: one row per month. The query saves the pivot as a view so the unpivot can read it.
CREATE VIEW category_by_month AS
SELECT category,
sum(amount) FILTER (WHERE month = date '2026-01-01') AS jan,
sum(amount) FILTER (WHERE month = date '2026-02-01') AS feb,
sum(amount) AS total
FROM sales
GROUP BY category;
SELECT * FROM category_by_month ORDER BY category;
SELECT p.category, v.month, v.amount
FROM category_by_month p
CROSS JOIN LATERAL (VALUES ('2026-01', p.jan), ('2026-02', p.feb))
AS v(month, amount)
ORDER BY p.category, v.month;docker exec -i sql-lab psql -U postgres -d reports -X -q < pivot.sql category | jan | feb | total
----------+--------+--------+--------
books | 270.00 | 160.00 | 430.00
games | 130.00 | 110.00 | 240.00
(2 rows)
category | month | amount
----------+---------+--------
books | 2026-01 | 270.00
books | 2026-02 | 160.00
games | 2026-01 | 130.00
games | 2026-02 | 110.00
(4 rows)The pivot has one row per category and the unpivot gives back one row per category and month, four in all. A useful self-test for any pivot: the month columns of each row must add up to total. If a month had no sales for a category, its cell would be NULL, not 0, because sum over no rows is NULL; wrap it in coalesce(..., 0) when the report should show zeros.
06. Step 5: The top two cities per region with LATERAL
LATERAL also solves "top N per group" cleanly. For each region on the left, the subquery on the right runs with that region as a parameter, sorts its cities by revenue and keeps two with LIMIT. The extra city in ORDER BY breaks ties the same way on every run. Use LEFT JOIN LATERAL (...) ON true instead of CROSS JOIN if groups with no rows on the right must still appear.
SELECT r.region, t.city, t.revenue
FROM (SELECT DISTINCT region FROM sales) AS r
CROSS JOIN LATERAL (
SELECT city, sum(amount) AS revenue
FROM sales s
WHERE s.region = r.region AND s.city IS NOT NULL
GROUP BY city
ORDER BY revenue DESC, city
LIMIT 2
) AS t
ORDER BY r.region, t.revenue DESC;docker exec -i sql-lab psql -U postgres -d reports -X -q < topn.sql region | city | revenue
--------+--------+---------
north | Leeds | 270.00
north | York | 100.00
south | Bath | 150.00
south | Exeter | 120.00
(4 rows)Hull, with 10, is the third city in the north and is left out. The same answer is possible with row_number() OVER (PARTITION BY region ORDER BY revenue DESC) in a CTE and WHERE rn <= 2 outside; compare the plans on your own data before choosing.
07. Step 6: Prove that a rewritten report returns the same rows
A colleague rewrote the city report to take each city's region from a reference table, cities, instead of from the sales rows. Before the new version replaces the old one, compare the two results. The set operators do this. A EXCEPT B returns the rows of A that do not appear in B, comparing whole rows; A INTERSECT B returns rows in both; A UNION B returns rows in either. They remove duplicates unless you add ALL. A difference in either direction is a problem, so run EXCEPT both ways and label the sides.
CREATE TEMP VIEW report_old AS
SELECT region, coalesce(city, '(unknown)') AS city, sum(amount) AS revenue
FROM sales GROUP BY region, city;
CREATE TEMP TABLE cities (city text PRIMARY KEY, region text NOT NULL);
INSERT INTO cities VALUES
('Leeds', 'north'), ('York', 'north'), ('Bath', 'south'), ('Exeter', 'south');
CREATE TEMP VIEW report_new AS
SELECT c.region, c.city, sum(s.amount) AS revenue
FROM sales s JOIN cities c ON c.city = s.city
GROUP BY c.region, c.city;
SELECT 'only in old' AS side, * FROM (SELECT * FROM report_old
EXCEPT SELECT * FROM report_new) a
UNION ALL
SELECT 'only in new', * FROM (SELECT * FROM report_new
EXCEPT SELECT * FROM report_old) b
ORDER BY side, region, city;
SELECT count(*) AS rows_in_both
FROM (SELECT * FROM report_old INTERSECT SELECT * FROM report_new) i;
-- duplicates: EXCEPT ALL subtracts counts, EXCEPT compares distinct rows
SELECT x FROM (VALUES (1), (1), (2)) a(x)
EXCEPT ALL
SELECT x FROM (VALUES (1), (2)) b(x);docker exec -i sql-lab psql -U postgres -d reports -X -q < compare.sql side | region | city | revenue
-------------+--------+-----------+---------
only in old | north | (unknown) | 20.00
only in old | north | Hull | 10.00
(2 rows)
rows_in_both
--------------
4
(1 row)
x
---
1
(1 row)The new report lost two rows. The inner join to cities drops the sale with no city and the Hull sale, because Hull is missing from the reference table: 30 of revenue would silently vanish from the north. Four rows match. The last query shows why ALL matters when duplicates are meaningful: the left side has two 1s and the right one, so one 1 remains; plain EXCEPT would return nothing. Before you trust a comparison, also check that both queries return the same columns in the same order and with comparable types, because set operators match columns by position, not by name.
08. Check your understanding
09. Apply it
The practice project asks for a category-by-month revenue pivot and tests that compare outputs with expected results. Build both:
- Add March data, extend the pivot and make every empty cell show 0.
- Write the expected pivot rows as a
VALUESlist and assert, withEXCEPTin both directions, that your query returns exactly those rows. - Produce one report with region subtotals, category subtotals and a grand total using
GROUPING SETS, labelled withgrouping(). - Fix
report_newso that the comparison in step 6 returns no differences, and keep the comparison as a test.
10. Review prompt
Without looking back, answer:
- Which grouping sets do
ROLLUP (a, b)andCUBE (a, b)expand to? - Why do subtotal rows need
grouping(), and what doesgrouping(a, b) = 3mean? - How do you pivot rows into columns in PostgreSQL, and how do you turn them back into rows?
- Why do you run
EXCEPTin both directions when comparing two reports, and when do you needEXCEPT ALL?
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.