Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

SQL Top Spenders by Month

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

Your question is SQL Top Spenders by 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

TikTok Shop needs a monthly leaderboard of its highest-spending users. Write a PostgreSQL query that returns the top three users by completed purchase spend for each calendar month.

Requirements

  1. Join users to transactions using user_id.
  2. Include only transactions with status = 'completed' and non-null amounts.
  3. Aggregate spending by calendar month and user, then rank users within each month by total spend descending. Break ties with the smaller user_id.
  4. Return up to three users per month, ordered chronologically and then by rank.

Schema

users
ColumnTypeDescription
user_idPKINTEGERUnique user identifier
display_nameVARCHAR(100)User-facing display name
emailVARCHAR(255)User email address
transactions
ColumnTypeDescription
transaction_idPKINTEGERUnique transaction identifier
user_idINTEGERUser associated with the transaction
purchased_atTIMESTAMPTimestamp when the purchase occurred
amountNUMERIC(12,2)Purchase amount
statusVARCHAR(20)Transaction processing status
Tablesuserstransactions
Your solutionPostgreSQL
You need to log in / sign up to run or submit.
Run a query to see results