Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: Performance & internals
Stage 5: Specialization

Part 08 / Stage 2

Analytics patterns

Goal: The standard analytics questions — top-N per group, duplicates, growth, empty-month-proof reports, cohorts, funnels, streaks, medians, pivots, subtotals — each as a pattern you can re-apply to any schema. Time: ~2.5 hours

What you will learn

  • Top-N per group, the complete pattern
  • Finding duplicates, and keeping exactly one of each
  • Period-over-period growth with LAG
  • Date spines: generate_series, so months with zero sales still appear
  • Cohort retention by first-order month
  • Funnels from an events table
  • Gaps and islands: consecutive-day streaks
  • Medians and percentiles: percentile_cont / percentile_disc
  • Pivoting rows to columns with FILTER
  • Subtotals: GROUPING SETS, ROLLUP, CUBE

These lean on everything since Part 5 — this is where the joins, CTEs and windows pay rent. Everything runs on shopdb.

Topics in this part

Practice

SQL workbench — write and run queries here

Press Run and PostgreSQL loads right in your browser (a one-time download of about 16 MB; after that it works offline). It comes seeded with shopdb, and statements share one session per page — like a psql window. Reset data rebuilds shopdb. Your queries never leave this page. Lessons were captured on PostgreSQL 17; the in-browser server is PostgreSQL 19 (via PGlite), so the rare output detail can differ.

Try each one yourself first, in psql against shopdb. Then check the solution.


Exercise 1: Top 2 earners per category

What to do: Each category's two biggest products by delivered revenue. (Categories with one seller show one row; a category whose products never sold shows none — why?)

Sample output:

 category_id |        name        | revenue 
-------------+--------------------+---------
           2 | SQL for Beginners  |  175.00
           2 | Postgres Deep Dive |  165.00
           3 | Desk Lamp          |   45.00
           4 | Laptop Pro 14      | 2400.00
           5 | Phone X            |  799.00
           5 | Phone Lite         |  399.00
           6 | Chef Knife         |   80.00
(7 rows)

💡 Hint: aggregate first, then ROW_NUMBER over PARTITION BY category_id, then keep rn <= 2. Category 1's only product never sold — no rows in, no rows out.


Show the solution to Exercise 1
-- Exercise 1: Top 2 earners per category
WITH product_revenue AS (
  SELECT p.category_id, p.name,
         sum(oi.quantity * oi.unit_price) AS revenue
  FROM order_items oi
  JOIN orders o   ON o.order_id = oi.order_id
  JOIN products p ON p.product_id = oi.product_id
  WHERE o.status = 'delivered'
  GROUP BY p.category_id, p.name
),
ranked AS (
  SELECT *, ROW_NUMBER() OVER (PARTITION BY category_id
                               ORDER BY revenue DESC) AS rn
  FROM product_revenue
)
SELECT category_id, name, revenue
FROM ranked WHERE rn <= 2
ORDER BY category_id, revenue DESC;

Exercise 2: Clean the import

Scenario: A price file arrived with the same SKU several times (build it with VALUES: chai ×3, coffee, tea — different dates). What to do: Keep one row per SKU — the newest — using the keep-one pattern.

Sample output:

  sku   | price | imported_on 
--------+-------+-------------
 chai   |   130 | 2025-06-04
 coffee |   150 | 2025-06-01
 tea    |    90 | 2025-06-03
(3 rows)

💡 Hint: ROW_NUMBER() OVER (PARTITION BY sku ORDER BY imported_on DESC), keep rn = 1.


Show the solution to Exercise 2
-- Exercise 2: Clean the import
WITH imports AS (
  SELECT * FROM (VALUES
    ('chai',   120, DATE '2025-06-01'),
    ('coffee', 150, DATE '2025-06-01'),
    ('chai',   125, DATE '2025-06-02'),
    ('tea',     90, DATE '2025-06-03'),
    ('chai',   130, DATE '2025-06-04')
  ) AS t(sku, price, imported_on)
),
numbered AS (
  SELECT *, ROW_NUMBER() OVER (PARTITION BY sku
                               ORDER BY imported_on DESC) AS rn
  FROM imports
)
SELECT sku, price, imported_on
FROM numbered WHERE rn = 1
ORDER BY sku;

Exercise 3: Growth that survives empty months

What to do: Month-over-month growth of delivered revenue for January–June 2025 — including May and June, which have no sales and must appear as 0 with honest growth figures.

Sample output:

   month    | revenue | growth_pct 
------------+---------+------------
 2025-01-01 | 2069.00 |           
 2025-02-01 |  135.00 |      -93.5
 2025-03-01 |  150.00 |       11.1
 2025-04-01 | 1709.00 |     1039.3
 2025-05-01 |       0 |     -100.0
 2025-06-01 |       0 |           
(6 rows)

💡 Hint: three CTEs — spine, revenue, spined (COALESCE) — then LAG with NULLIF. June's blank: dividing by May's 0 is honestly unknowable.


Show the solution to Exercise 3
-- Exercise 3: Growth that survives empty months
WITH months AS (
  SELECT generate_series(DATE '2025-01-01', DATE '2025-06-01',
                         INTERVAL '1 month')::date AS month
),
revenue AS (
  SELECT date_trunc('month', o.order_date)::date AS month,
         sum(oi.quantity * oi.unit_price) AS revenue
  FROM orders o
  JOIN order_items oi ON oi.order_id = o.order_id
  WHERE o.status = 'delivered'
  GROUP BY 1
),
spined AS (
  SELECT m.month, COALESCE(r.revenue, 0) AS revenue
  FROM months m
  LEFT JOIN revenue r ON r.month = m.month
)
SELECT month, revenue,
       round(100.0 * (revenue - LAG(revenue) OVER (ORDER BY month))
             / NULLIF(LAG(revenue) OVER (ORDER BY month), 0), 1) AS growth_pct
FROM spined
ORDER BY month;

Exercise 4: The site funnel

What to do: Count distinct customers at the view, cart and purchase steps, plus the view-to-cart conversion percentage — all in one pass over events.

Sample output:

 viewed | carted | purchased | view_to_cart_pct 
--------+--------+-----------+------------------
      3 |      2 |         2 |               67
(1 row)

💡 Hint: count(DISTINCT customer_id) FILTER (WHERE ...) three times.


Show the solution to Exercise 4
-- Exercise 4: The device funnel
SELECT count(DISTINCT customer_id) FILTER (WHERE event_type = 'view')     AS viewed,
       count(DISTINCT customer_id) FILTER (WHERE event_type = 'cart')     AS carted,
       count(DISTINCT customer_id) FILTER (WHERE event_type = 'purchase') AS purchased,
       round(100.0 * count(DISTINCT customer_id) FILTER (WHERE event_type = 'cart')
             / NULLIF(count(DISTINCT customer_id) FILTER (WHERE event_type = 'view'), 0), 0)
         AS view_to_cart_pct
FROM events;

Exercise 5: Streak hunter

What to do: From login dates July 1–2, 4–7 and 10 (VALUES), find every streak — longest first.

Sample output:

 streak_start | streak_end | days 
--------------+------------+------
 2025-07-04   | 2025-07-07 |    4
 2025-07-01   | 2025-07-02 |    2
 2025-07-10   | 2025-07-10 |    1
(3 rows)

💡 Hint: login_date - row_number()::int is the island key.


Show the solution to Exercise 5
-- Exercise 5: Streak hunter
WITH logins AS (
  SELECT * FROM (VALUES
    (DATE '2025-07-01'), (DATE '2025-07-02'),
    (DATE '2025-07-04'), (DATE '2025-07-05'), (DATE '2025-07-06'), (DATE '2025-07-07'),
    (DATE '2025-07-10')
  ) AS t(login_date)
),
marked AS (
  SELECT login_date,
         login_date - (ROW_NUMBER() OVER (ORDER BY login_date))::int AS island
  FROM logins
)
SELECT min(login_date) AS streak_start,
       max(login_date) AS streak_end,
       count(*)        AS days
FROM marked
GROUP BY island
ORDER BY days DESC, streak_start;

Exercise 6: Typical vs average order

What to do: In one query over per-order totals: the average, the interpolated median, and the median as an actual order value. Then say in one sentence what the gap means.

Sample output:

 average_order | median_order | median_actual 
---------------+--------------+---------------
        659.00 |          798 |        798.00
(1 row)

💡 Hint: derived table of per-order sums, then percentile_cont(0.5) / percentile_disc(0.5) WITHIN GROUP. The average sits below the median here — the small top-up orders weigh it down.


Show the solution to Exercise 6
-- Exercise 6: Typical vs average order
WITH per_order AS (
  SELECT order_id, sum(quantity * unit_price) AS order_total
  FROM order_items
  GROUP BY order_id
)
SELECT round(avg(order_total), 2) AS average_order,
       percentile_cont(0.5) WITHIN GROUP (ORDER BY order_total) AS median_order,
       percentile_disc(0.5) WITHIN GROUP (ORDER BY order_total) AS median_actual
FROM per_order;

Exercise 7: The status board

What to do: Months down the side, one column per order status — the FILTER pivot.

Sample output:

   month    | delivered | shipped | pending | cancelled 
------------+-----------+---------+---------+-----------
 2025-01-01 |         2 |       0 |       0 |         0
 2025-02-01 |         1 |       1 |       0 |         0
 2025-03-01 |         1 |       0 |       1 |         1
 2025-04-01 |         2 |       0 |       0 |         0
(4 rows)

💡 Hint: four count(*) FILTER (WHERE status = ...) columns over a month GROUP BY.


Show the solution to Exercise 7
-- Exercise 7: The status board
SELECT date_trunc('month', order_date)::date AS month,
       count(*) FILTER (WHERE status = 'delivered') AS delivered,
       count(*) FILTER (WHERE status = 'shipped')   AS shipped,
       count(*) FILTER (WHERE status = 'pending')   AS pending,
       count(*) FILTER (WHERE status = 'cancelled') AS cancelled
FROM orders
GROUP BY 1
ORDER BY month;

Exercise 8: Subtotals, honestly labelled

What to do: Orders per customer city with a grand-total row — where Sara's NULL city shows as Unknown and the total row as ALL, never confused with each other.

Sample output:

  city   | orders 
---------+--------
 Pune    |      3
 Chennai |      2
 Delhi   |      2
 London  |      1
 Unknown |      1
 ALL     |      9
(6 rows)

💡 Hint: GROUP BY ROLLUP (city) with CASE WHEN GROUPING(city) = 1 THEN 'ALL' ELSE COALESCE(city, 'Unknown') END — this is exactly why GROUPING() exists.

Show the solution to Exercise 8
-- Exercise 8: Subtotals in one pass
-- GROUPING() = 1 marks the rollup row, so a real NULL city could never
-- be mistaken for the total line.
SELECT CASE WHEN GROUPING(c.city) = 1 THEN 'ALL'
            ELSE COALESCE(c.city, 'Unknown') END AS city,
       count(o.order_id) AS orders
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.customer_id
GROUP BY ROLLUP (c.city)
ORDER BY GROUPING(c.city), orders DESC, city;

Common mistakes

Mistake What happens Fix
Time series without a spine Empty periods vanish instead of showing 0 generate_series + LEFT JOIN + COALESCE
Growth % without NULLIF Division by zero on a flat month NULLIF(LAG(...), 0)
Funnel counts without DISTINCT Busy users inflate every step count(DISTINCT customer_id) FILTER (...)
Treating ROLLUP's NULL as data Subtotals mistaken for "unknown" rows GROUPING(), or COALESCE a label
Reporting only averages Outliers masquerade as the typical case percentile_cont alongside avg
Top-N with RANK unthinkingly Ties overflow the N Pick ROW_NUMBER or RANK deliberately

Quick recap

  • Top-N per group takes three moves: aggregate, rank with a partitioned window, and filter outside.
  • Find duplicates with HAVING count(*) > 1, and keep exactly one of each with a partitioned ROW_NUMBER = 1.
  • Growth reports come from LAG with a NULLIF guard; missing months come back when you LEFT JOIN the facts onto a generate_series spine and COALESCE the gaps to zero.
  • Cohorts group by first-activity month; funnels are DISTINCT FILTER counts.
  • For streaks, value - row_number() gives every island one label, and GROUP BY on that label does the rest.
  • Medians come from percentile_cont/disc WITHIN GROUP, pivots from FILTER columns, and subtotals from ROLLUP or GROUPING SETS — with GROUPING() to keep the labels honest.

Checklist

Before the Stage 2 project, make sure you can:

  • Produce each category's top 2 products by revenue.
  • De-duplicate a messy import, keeping the earliest copy.
  • Build a month-over-month growth report that survives empty months.
  • Count a view-to-cart-to-purchase funnel with conversion rates.
  • Explain the islands trick from memory.
  • Add a grand-total row without a second query.

Read more: the official set-returning functions reference (generate_series), ordered-set aggregates (percentile_cont), and the GROUPING SETS chapter.

Search the guide