Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Sales by Month and User

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

Your question is Sales by Month and User. 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

Edmunds wants a monthly view of sales performance by user for the current month and the two preceding calendar months. Write a PostgreSQL query that produces one row for every Edmunds user in each of those three months, including users with no sales.

Requirements

  1. Generate the three-month reporting window dynamically from CURRENT_DATE.
  2. Aggregate sales amount, sales quantity, and transaction count by calendar month and user.
  3. Show zero totals for users without sales in a month.
  4. Use LAG to calculate the prior month's sales amount and sales change.
  5. Rank users within each month by total sales amount, highest first, with user ID as a deterministic tie-breaker.
  6. Return results ordered by month, rank, and user ID.

Schema

users
ColumnTypeDescription
user_idPKINTEGEREdmunds user identifier
user_nameVARCHAR(100)User display name
sales
ColumnTypeDescription
sales_idPKINTEGERUnique sale identifier
user_idINTEGERUser who made the sale
sales_dateDATEDate the sale occurred
sales_amountNUMERIC(12,2)Sale amount, including refunds
sales_quantityINTEGERNumber of units in the sale
Tablesuserssales
Your solutionPostgreSQL
You need to log in / sign up to run or submit.
Run a query to see results