Skip to content
mentoor

Topic 3 of 5 · 5 min read

Analytical SQL with windows and rollups

Goal: Write a cohort or running-total report with window functions and verify one of its rows by hand.

A window function computes a value across related rows without collapsing them, so a report can show each order next to its running total, rank or previous value in a single query. Rollups and grouping sets add subtotals the same way: one query, several levels of detail.

Check yourself · 1 of 3

What is the main difference between a window function and GROUP BY?

Choose one answer

Why it matters

Reporting questions are rarely plain GROUP BY. "Revenue per day and the running total this month", "the latest order per customer", "totals per country and a grand total" all need more. Writing them as self-joins or subqueries is slow and easy to get wrong. Assistants write them often, so you must be able to read them and check them.

How to do it

  1. Window frame. sum(amount) OVER (PARTITION BY customer_id ORDER BY created_at) restarts for each customer and adds up in time order. Say the frame when it matters: ROWS BETWEEN 6 PRECEDING AND CURRENT ROW is a 7-row moving window.
  2. Ranking. row_number(), rank() and dense_rank() differ on ties. Use row_number() when you need exactly one row.
  3. QUALIFY. DuckDB, ClickHouse-compatible dialects, BigQuery and Snowflake let you filter on a window result directly: QUALIFY row_number() OVER (...) = 1. PostgreSQL has no QUALIFY; wrap the query in a subquery instead.
  4. Subtotals. GROUP BY ROLLUP (country, city) returns city rows, country subtotals and a grand total. GROUPING SETS lets you pick the exact combinations.
  5. Buckets. date_trunc('week', created_at) groups by week. Decide the time zone first.
  6. Approximate counts. approx_count_distinct(user_id) is much cheaper than exact count(DISTINCT ...) on huge data, with a small, documented error. Use exact counts for money.
  7. Verify one row by hand. Pick one customer, add their rows yourself, and compare.

Before and after

The latest order per customer, written as a self-join:

SELECT o.* FROM orders o
JOIN (SELECT customer_id, max(created_at) AS m FROM orders GROUP BY customer_id) x
  ON x.customer_id = o.customer_id AND x.m = o.created_at;

If two orders share a timestamp, a customer appears twice. With a window and a tie-break:

SELECT *
FROM orders
QUALIFY row_number() OVER (
  PARTITION BY customer_id ORDER BY created_at DESC, order_id DESC) = 1;

What goes wrong

  • Missing ORDER BY in the window. A running total without an order sums in an arbitrary sequence.
  • Default frame surprises. With ORDER BY and no frame, ties on the sort key are included together, so two rows on the same day show the same running total.
  • Time zones in buckets. A UTC midnight cut moves late-evening orders into the next day for local reports.
  • Approximate counts in finance. An estimate that is fine for traffic is wrong for invoices.

Examples

Running total per customer

SELECT customer_id, created_at, amount,
       sum(amount) OVER (
         PARTITION BY customer_id
         ORDER BY created_at, order_id
       ) AS running_total
FROM orders;

Take customer 17 and add their first three amounts on a calculator. The third running_total must equal that sum.

Totals per country with a grand total

SELECT country, city, sum(amount) AS revenue
FROM orders
GROUP BY ROLLUP (country, city)
ORDER BY country, city;

Rows where city is null are country subtotals; the row where both are null is the grand total. It should equal an ungrouped sum(amount).

Key points

  • A window function adds a per-row value over related rows without collapsing them like GROUP BY does.
  • Always give a window an ORDER BY, and say the frame when order or ties matter.
  • Use row_number() with a tie-break column when you need exactly one row per group.
  • ROLLUP and GROUPING SETS return subtotals and a grand total in one query.
  • Check one customer or one day by hand before you trust a window query.

Common mistakes

  • Leaving ORDER BY out of a running-total window.
  • Using rank() where one row per group is needed, so ties return several rows.
  • Bucketing timestamps by UTC when the report is for a local day.
  • Using approximate distinct counts for figures that must be exact.

Check yourself · 2 of 3

A running total shows the same value on two orders placed on the same day. The window is ORDER BY order_date with no frame. What causes this and what fixes it?

Choose one answer

Check yourself · 3 of 3

You need one latest order per customer, and two orders can share a timestamp. Which approach returns exactly one row each?

Choose one answer

Practice items, not counted towards your mastery.

Start here

More for this topic