How do you get the 3 latest orders of each customer (top-N per group)?
Short answer
Number rows within each group with ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY created_at DESC), then filter rn <= 3 in an outer query. When each customer has very many orders, use LATERAL with an index.
3 points to say:
ROW_NUMBER, filter in the outer query.- Many rows per group:
LATERAL+ index. - Add
idtoORDER BY.
Keep reading the deep dive
Create a free account to read the full explanation and follow-up questions, mark questions as studied and review them on a schedule.