Interview Questions/SQL/Top 3 Products by Revenue per Category (with RANK)

Top 3 Products by Revenue per Category (with RANK)

Preview mode. Log in to edit, run, submit, and save progress.

Medium

Description

You are given a table of product sales. Each row contains a product name, its category, and its total revenue. Write a SQL query to return the top 3 revenue-ranked products per category using RANK() (not ROW_NUMBER or DENSE_RANK). If products tie, they share the same rank and both are included. A tie at rank 1 between two products means rank 3 is the next product (rank 2 is skipped). Return category, product, revenue, and rnk for all rows where rnk <= 3, ordered by category then rnk then product. Table: ProductSales

Column NameTypeDescription
idINTPrimary key
productVARCHARProduct name
categoryVARCHARProduct category
revenueINTTotal revenue

Database Schema (Inferred)

ProductSales

Column NameExample Value
id1
productP1
categoryElectronics
revenue5000

Example

ProductSales

idproductcategoryrevenue
1P1Electronics5000
2P2Electronics8000
3P3Electronics8000
4P4Electronics3000
5P5Electronics7000
6P6Clothing2000
7P7Clothing4000
8P8Clothing4000
9P9Clothing1000
10P10Food500
11P11Food900

Output

categoryproductrevenuernk
ClothingP740001
ClothingP840001
ClothingP620003
ElectronicsP280001
ElectronicsP380001
ElectronicsP570003
FoodP119001
FoodP105002

Explanation:

RANK() assigns the same rank to ties and skips subsequent ranks. P2 and P3 both get rank 1, so P5 gets rank 3 (rank 2 is skipped). Only rnk <= 3 are included.

Approach hint

Start with a simple approach, explain the trade-off, then move toward a cleaner or more scalable solution.

Common mistake

Skipping assumptions, edge cases, or trade-offs can make an otherwise good answer feel incomplete.

SQL Editor
Loading...

ProductSales

idproductcategoryrevenue
1P1Electronics5000
2P2Electronics8000
3P3Electronics8000
4P4Electronics3000
5P5Electronics7000
6P6Clothing2000
7P7Clothing4000
8P8Clothing4000
9P9Clothing1000
10P10Food500
11P11Food900

Output

categoryproductrevenuernk
ClothingP740001
ClothingP840001
ClothingP620003
ElectronicsP280001
ElectronicsP380001
ElectronicsP570003
FoodP119001
FoodP105002