← Problems5. Top N products per categoryEasySQL
00:00 / 20:00

Top N products per category

Easy27% solve itAsked at Microsoft

Return the three highest-revenue products in each category.

Input schema

products category string product_id bigint revenue numeric

Constraints

  • Three per category at most; a category with fewer returns all of them
  • Ties on revenue break on product_id ascending
  • Order by category, then revenue descending, then product_id ascending

Example 1three per category, ordered by revenue

Input · products
revenuecategoryproduct_id
500books1
300books2
100books3
90toys4
Output
categoryproduct_idrevenue
books1500
books2300
books3100
toys490

Example 2a category with more than three products

Input · products
revenuecategoryproduct_id
10books1
40books2
30books3
20books4
Output
categoryproduct_idrevenue
books240
books330
books420

Topics

aggregation

Similar problems

Community-reported interview topic. Not an official company question and no affiliation is implied.

solution.sql
Loading editor…
Draft not saved yet · Spaces 4 · UTF-8⌘↵ run ⌘⇧↵ submit
Nothing run yet

Run against the public tests, or submit to score against all of them.