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

Part 08 / Topic 1 of 10

Top-N per group

Part 7 ended with top-1 per group. The full pattern is identical with <= N — each category's two biggest earners by delivered revenue:

WITH product_revenue AS (
  SELECT p.category_id, p.name,
         sum(oi.quantity * oi.unit_price) AS revenue
  FROM order_items AS oi
  JOIN orders   AS o ON o.order_id = oi.order_id
  JOIN products AS 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;
 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)

The three steps are always the same: aggregate to the grain you rank at, window the rank per group, then filter outside. Choose the ranking function deliberately: ROW_NUMBER for "exactly N", RANK for "N plus ties".

🧪 Quick quiz — answer from memory, then check.

  1. The three steps of top-N per group?
  2. When would RANK beat ROW_NUMBER here?
Show the answers
  1. Aggregate first, rank with a PARTITION BY window, then filter the rank in an outer query.
  2. When tied values should all make the cut ("top 3, ties included").

Done here? The practice set for Part 8 — 8 exercises with solutions — is on the part page.

Search the guide