Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

SQL Top 3 Customers Per Month

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

Your question is SQL Top 3 Customers Per Month. 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

PA Consulting wants a monthly view of its highest-value client accounts. Write a PostgreSQL query that calculates completed-order revenue for each client and returns the top three clients in every month.

Requirements

  1. Join customers to orders using customer_id.
  2. Include only orders with status = 'completed' and group revenue by calendar month and client.
  3. Rank clients independently within each month using a deterministic ordering, then return ranks 1 through 3.
  4. Return the month as YYYY-MM, client name, total revenue, and monthly rank, ordered by month and rank.

Schema

customers
ColumnTypeDescription
customer_idPKINTEGERUnique client identifier
customer_nameVARCHAR(120)Client account name
orders
ColumnTypeDescription
order_idPKINTEGERUnique order identifier
customer_idINTEGERClient associated with the order
order_dateDATEDate the order was placed
amountNUMERIC(12,2)Order revenue
statusVARCHAR(20)Order processing status
Tablescustomersorders
Your solutionPostgreSQL
You need to log in / sign up to run or submit.
Run a query to see results