Chapter 8 · Window Functions
22. Top 3 Products per Category by Revenue
Hard40 XPE-Commerce
Find the top 3 products by total revenue in each category. Revenue is calculated from order_items (quantity * unit_price - discount, where discount is the dollar amount taken off the line). Use DENSE_RANK to rank and filter to rank <= 3. Show category_id, product name, total revenue, and rank. Sort by category_id, then rank.
Tables
- 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.