Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Top Products SQL by Category

MediumSQL · PostgreSQL00:00
Practice interviewer
In session
5 left
00:00

Your question is Top Products SQL by Category. Start with the requirements and the three tables on the right.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.

Problem

HCLTech's retail analytics team needs a quarterly product leaderboard for executive reporting. Write a PostgreSQL query that evaluates product sales during the previous completed calendar quarter relative to the current date.

Calculate total units sold and total revenue for each product, associate every product with its category, and assign a position within that category. Revenue is calculated as quantity * unit_price for each order item.

Output

  1. One row per qualifying product, with columns category_name, product_name, total_units_sold, total_revenue, and revenue_rank.
  2. Include only products with sales in the previous completed calendar quarter.
  3. Return no more than three products per category.
  4. Sort by category name alphabetically, then leaderboard position ascending.
  5. Within each category, order by total revenue descending, total units sold descending, and product name ascending to resolve ties.

Schema

categories
ColumnTypeDescription
category_idPKINTPrimary key for the product category
category_nameVARCHAR(100)Display name of the category
products
ColumnTypeDescription
product_idPKINTPrimary key for the product
category_idINTReferences categories.category_id
product_nameVARCHAR(150)Display name of the product
order_items
ColumnTypeDescription
order_item_idPKINTPrimary key for the order line
product_idINTReferences products.product_id
order_dateDATEDate on which the item was sold
quantityINTNumber of units sold
unit_priceNUMERIC(10,2)Sale price per unit
Tablescategoriesproductsorder_items
Your solutionPostgreSQL
You need to log in / sign up to run or submit.
Run a query to see results