Highest Grossing Items

ASKED IN INTERVIEW
4pts
Amazon

Problem Statement

Amazon needs to identify its best-performing products to optimize inventory.

Write an SQL query to find the top 2 highest-grossing products (by total revenue) for each category in each year.

Rules:

  • Revenue is calculated as the sum of (unit_price * quantity) for all sales of a product.
  • If there is a tie in revenue, the product with the lower product_id should be ranked higher.
  • A year is defined by the transaction_date.
  • Return columns: year, category_name, product_name, total_revenue.
  • Results must be sorted by year in descending order, then by category_name in ascending order, and finally by total_revenue in descending order.
Tests your understanding of
Window Functions, Ranking, Subqueries and Aggregation

Input Tables

categories
category_id(INTEGER)category_name(VARCHAR)
1Electronics
2Home Decor
products
product_id(INTEGER)product_name(VARCHAR)category_id(INTEGER)
101Laptop1
102Smartphone1
103Tablet1
201Lamp2
202Vase2
203Rug2
sales
sale_id(INTEGER)product_id(INTEGER)unit_price(DECIMAL)quantity(INTEGER)transaction_date(TIMESTAMP)
1101100022023-01-10 10:00:00
210280052023-02-15 11:00:00
310350012023-03-20 12:00:00
420150102023-01-05 09:00:00
520240202023-05-10 14:00:00
620315022023-06-01 15:00:00
7101100012024-01-10 10:00:00
810280012024-01-11 11:00:00
9103500102024-01-12 12:00:00
102015052024-02-01 10:00:00

Expected Output

year(INTEGER)category_name(VARCHAR)product_name(VARCHAR)total_revenue(DECIMAL)
2024ElectronicsTablet5000
2024ElectronicsLaptop1000
2024Home DecorLamp250
2023ElectronicsSmartphone4000
2023ElectronicsLaptop2000
2023Home DecorVase800
2023Home DecorLamp500

Tags

MediumASKED IN INTERVIEWWindow FunctionsRankingSubqueriesAggregation
20-25 min
45%

Hints