04, 11 chapters
windows, grouping and recursion
everything.analytics
windows, grouping and recursion
the queries that make spreadsheets jealous. window functions, grouping sets and recursive CTEs.
- 04.01FILTER and pivotingcount(*) FILTER (WHERE ...), the SUM(CASE ...) it replaced, and rows turned into columns.
- 04.02ROLLUP, CUBE and GROUPING SETSsubtotals and a grand total in one query, and GROUPING() to tell their NULLs from yours.
- 04.03percentiles, medians and string_aggaggregates that care about order: WITHIN GROUP, percentile_cont vs percentile_disc, and ordered string_agg.
- 04.04window functionsaggregates that don't collapse rows. OVER, PARTITION BY, and where windows sit in the logical order.
- 04.05row_number, rank and dense_rankthree ways to number rows. they only disagree on ties, which is exactly when it matters.
- 04.06LAG, LEAD and running totalsthe previous row, the next row, and a sum of every row so far.
- 04.07window framesROWS, RANGE and GROUPS. the default frame that makes last_value look broken.
- 04.08top n per groupthe three best sellers in every category: row_number, LATERAL and DISTINCT ON, compared on one plan.
- 04.09gaps and islandsstreaks, sessions and missing days. the row_number subtraction trick, stepped through.
- 04.10recursive CTEsa query that feeds on its own output. walking an org chart, depth first or breadth first, with CYCLE for loops.
- 04.11generate_series and calendarsrows from nothing: date spines, filling gaps with zeros, and fake data that's the same every run.