SQL interview question: top 3 categories in each city

MediumTop-N per group

Problem

Shared data rules

For each city, find the three categories with the highest revenue in September 2026. Equal revenue shares a place, so a city can have more than three rows.

Formula

Example

Input: orders
order_idstatuscitycreated_at
701deliveredBoston2026-09-01 10:15
702deliveredBoston2026-09-10 15:00
Input: order_items
order_idcategoryquantityprice_usd
701Meat & seafood118
701Produce43
701Sweets & snacks110
702Beverages25
702Pantry14
Output
citycategoryrevenuernk
BostonMeat & seafood181
BostonProduce122
BostonBeverages103
BostonSweets & snacks103

Boston’s revenue: meat $18, produce 4 × $3 = $12, beverages 2 × $5 and sweets — $10 each, so they share 3rd place. Pantry at $4 is fifth and isn’t in the answer.

Solve it free

Your query runs on PostgreSQL in your browser. No sign-up needed.

Skills it tests

More interview questions

All questions