Dataford
Popular roles
Software EngineerData AnalystData ScientistData EngineerBusiness AnalystAI EngineerMachine Learning EngineerProduct Manager
Browse
Browse All RolesEvery role hub, from analyst to MLBrowse All CompaniesCompany-specific interview loopsAll Interview GuidesThe full guide library
Top questions by role
Software EngineerData AnalystData ScientistData EngineerBusiness AnalystAI EngineerMachine Learning EngineerProduct Manager
Top questions by skill
SQLPythonStatisticsMachine LearningA/B TestingSystem DesignGenerative AIProduct SenseMetricsBehavioral
Browse all questions →Try a mock interview
ExperiencesCoaching
New
Practice
Mock InterviewsTimed interview simulations with feedbackSuccess PathYour 6-week structured planModulesCurated lessons by topicWebinarsTalks from ex-Big Tech data leadsPlaygroundA free-form scratch editor
Learn
BlogInterview strategy and career adviceTech Job Market ReportHiring trends across data and AI rolesFor UniversitiesDataford for career centersAbout DatafordWho we are and how we build
Pricing
Start free
SQL Top 3 Customers Per Month
00:00
5 left

SQL Top 3 Customers Per Month

MediumSQL · PostgreSQL

Problem

A company 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.

Output details

  • Return columns named revenue_month, customer_name, total_revenue, and revenue_rank, in that order.
  • Order results by revenue_month ascending, then revenue_rank ascending.
  • Break equal revenues by ascending customer_id.

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
Interviewer

Whenever you're ready, walk me through your approach or go straight to the code. The requirements and the two tables are in the Question tab.

Sign up free to run or submit. Log in
CodePostgreSQL
Sign up free to run your code. Your draft is saved.Run with a free accountLog inLn 1
Run your query to see results here.