Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Top Products by Revenue per Category

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

Your question is Top Products by Revenue per Category. Start with the requirements and the two 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

Clip wants a monthly view of its highest-revenue products by category. Write a PostgreSQL query that aggregates completed sales and uses a window function to rank products within each category and month.

Requirements

  1. Join sales to products and calculate revenue as quantity * unit_price.
  2. Restrict the calculation to rows where status = 'completed', then aggregate revenue by product, category, and calendar month.
  3. Use ROW_NUMBER() or RANK() partitioned by category and month to identify the top three products. Break revenue ties with the product ID.
  4. Return the category, month, product name, total revenue, and rank, ordered by category, month, revenue descending, and product ID.

Schema

products
ColumnTypeDescription
product_idPKINTEGERUnique product identifier
product_nameVARCHAR(100)Clip product name
categoryVARCHAR(50)Product category
sales
ColumnTypeDescription
sale_idPKINTEGERUnique sale identifier
product_idINTEGERProduct sold
sold_atDATEDate of sale
quantityINTEGERUnits sold
unit_priceNUMERIC(10,2)Price per unit
statusVARCHAR(20)Sale processing status
Tablesproductssales
Your solutionPostgreSQL
You need to log in / sign up to run or submit.
Run a query to see results