SQL
Lab
Amazon Easy Ranking Tie Break

Best Selling
Product
By Category

Find the best-selling product in each category, using rating to break ties.

Table Schema

Inspect
Table

interactive
ColumnTypeDescription
product_idintegerUnique product identifier.
product_namestringName of the product.
category_namestringProduct category.
ColumnTypeDescription
product_idintegerProduct identifier.
sales_quantityintegerTotal units sold.
ratingdecimalProduct rating.

Sample Data

Input
Output

Sample Input: products
product_idproduct_namecategory_name
1LaptopElectronics
2PhoneElectronics
3Book ABooks
4Book BBooks
5TVElectronics
6Book CBooks
Sample Input: product_sales
product_idsales_quantityrating
12004.5
22504.2
33004.8
43004.6
52504.7
61004.9
Expected Output
category_nameproduct_name
BooksBook A
ElectronicsPhone

SQL Editor

Run
Query

postgresql
Waiting for query

category_nameproduct_name
BooksBook A
ElectronicsPhone

Hints

Unlock
Clues

Hint 01: Join products to product_sales using product_id.
Hint 02: Use ROW_NUMBER() or RANK() over each category.
Hint 03: Order by sales_quantity DESC, then rating DESC, and keep rank 1.

Solution

Locked
Answer

Solution is locked until you decide to reveal it. Try the editor first, then open this when you want the reference answer.

WITH ranked_products AS (
  SELECT
    p.category_name,
    p.product_name,
    ROW_NUMBER() OVER (
      PARTITION BY p.category_name
      ORDER BY ps.sales_quantity DESC, ps.rating DESC
    ) AS product_rank
  FROM products AS p
  JOIN product_sales AS ps
    ON p.product_id = ps.product_id
)
SELECT
  category_name,
  product_name
FROM ranked_products
WHERE product_rank = 1;

Explanation

Step By
Step

01

Join product details to sales data using product_id.

02

Rank products within each category by sales_quantity descending.

03

Use rating descending as the tie-breaker, then keep the top-ranked product.

Related Questions

Keep
Solving