Interview › Latest row
SQL interview: latest order per customer
MAX(order_date) then join back fails when two orders share that date. Number the rows.
Prompt. Return the most recent order row per customer (full row, not just the date).
Hint: ROW_NUMBER PARTITION BY customer_id ORDER BY order_date DESC
SELECT *
FROM (
SELECT o.*,
ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY order_date DESC, order_id DESC) AS rn
FROM Orders o
) x
WHERE rn = 1;
CROSS APPLY (SELECT TOP 1 …) is the same idea and sometimes reads better.
Then write it on a ticket
Monday is free. A colleague asks, you type, we mark it.
Clock in free