Chapter 9 · Interview Level
32. Top 3 Best-Selling Products Per Category
Hard40 XPE-Commerce
Find the top 3 best-selling products (by total quantity sold) in each category. Return category name, product name, total quantity sold, and the rank within the category. Use a CTE with a window function, then filter to rank <= 3. If two products sold the same quantity, rank them alphabetically by product name. Sort by category name, then rank.
Tables
- PKidINT
- nameTEXT
- descriptionTEXT
- PKidINT
- nameTEXT
- FKcategory_id→ categories.idINT
- priceREAL
- costREAL
- stock_quantityINT
- created_atTIMESTAMP
- PKidINT
- FKorder_id→ orders.idINT
- FKproduct_id→ products.idINT
- quantityINT
- unit_priceREAL
- discountREAL
Need help?
Ask Sol
AI tutor — looks at your current query and nudges you, without spoiling the answer.
Solution
Try the hints first — solving it yourself is what makes it stick.