Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

SQL Window Functions Ranking

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

Your question is SQL Window Functions Ranking. Start with the requirements and the four 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

Career Soft Solutions Pvt. uses a product revenue report to identify leading products each month. Write a PostgreSQL query that ranks products by revenue within every category and month.

Requirements

  1. Include only orders whose status is completed.
  2. Calculate product revenue as quantity * unit_price, aggregated by calendar month, category, and product.
  3. Use a window function to assign a deterministic rank within each month and category, ordering revenue descending and product_id ascending for ties.
  4. Return only the top three products in each category for each month, including categories with fewer than three qualifying products.
  5. Return results ordered by month, category, rank, and product ID.

Schema

categories
ColumnTypeDescription
category_idPKINTPrimary key for a product category
category_nameVARCHAR(80)Display name of the category
products
ColumnTypeDescription
product_idPKINTPrimary key for a product
product_nameVARCHAR(120)Product display name
category_idINTReference to categories.category_id
orders
ColumnTypeDescription
order_idPKINTPrimary key for an order
order_dateTIMESTAMPTimestamp when the order was placed
statusVARCHAR(20)Order processing status
order_items
ColumnTypeDescription
order_item_idPKINTPrimary key for an order line item
order_idINTReference to orders.order_id
product_idINTReference to products.product_id
quantityINTNumber of units in the line item
unit_priceNUMERIC(12,2)Price per unit at purchase time
Tablescategoriesproductsordersorder_items
Your solutionPostgreSQL
You need to log in / sign up to run or submit.
Run a query to see results