Interview › Top N per group
SQL interview: top 3 orders per customer (ROW_NUMBER)
“Top 3 per country” is the same pattern as “top 3 per customer.” Number the rows, then keep 1..3.
Prompt. Find the three highest-value orders for each customer. Include ties only if you meant RANK.
Hint: ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY total_amount DESC)
SELECT *
FROM (
SELECT o.*,
ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY total_amount DESC, order_id DESC) AS rn
FROM Orders o
) x
WHERE rn <= 3;
RANK keeps ties and can return more than 3. ROW_NUMBER always returns 3. Ask which they wanted.
Then write it on a ticket
Monday is free. A colleague asks, you type, we mark it.
Clock in free