SQL Quest › SQL Interview Questions › Window Functions
Top 3 Merchants Per Category by Spend
Top-N per group — the window question every analyst screen keeps. For each merchant category, rank merchants by their total card spend and keep the top three. Aggregate first (one row per merchant), then rank inside a CTE with ROW_NUMBER() OVER (PARTITION BY category ORDER BY total_spend DESC, merchant_id), then filter rank_in_category <= 3 outside it — a window function cannot sit in a WHERE clause.
Return category, name (merchant name), total_spend (SUM of amount, rounded to 2 decimals), and rank_in_category. Categories with fewer than three merchants return what they have. Order by category ascending, then rank_in_category ascending.
Solve it in the browser editor →
Runs on SQLite in your browser, graded against the expected result, no signup. A wrong answer gets a diagnosis, not just "incorrect".
Schema
transactions
| txn_id | account_id | amount | txn_at | merchant_id | lat | lng | status |
|---|---|---|---|---|---|---|---|
| 1 | 149 | 151.84 | 2026-03-04T12:39:39.078Z | 24 | 40.342 | -74.4092 | completed |
| 2 | 21 | 10.72 | 2026-03-04T13:04:50.641Z | 7 | 52.9366 | 13.3229 | completed |
| 3 | 35 | 158.78 | 2026-03-04T13:27:15.528Z | 25 | 52.7397 | 13.3134 | completed |
merchants
| merchant_id | name | category | country | risk_tier |
|---|---|---|---|---|
| 1 | BigBox Mart | Grocery | TR | high |
| 2 | Quick Stop | Electronics | JP | high |
| 3 | Aurora Cafe | Travel | TR | high |
Expected output: Clothing: Flux Online 1, Vespa Apparel 2, PillPath 3; Electronics: Quick Stop 1 ...
Hint
SELECT, Window Functions, ROW_NUMBER, and open the hint there if you stall.Concepts
SELECT Window Functions ROW_NUMBER PARTITION BY JOIN GROUP BY Window Functions + CTE
Practise the topic: SQL practice questions · Window function practice · JOIN practice · GROUP BY exercises · CTE practice · Ranking function practice
In these company practice sets
A SQL Quest challenge matched to patterns reported for these companies — not a question any of them has published.
Related questions
Where would this cost you points in an interview?
Ten questions, no signup: a Skillmap across nine SQL skills and the one to fix first.
Take the readiness test