Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

SQL for Cohort Ranking

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

Your question is SQL for Cohort Ranking. 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

Write a SQL query to rank users within each cohort by spend and return the top 3 per cohort.

Use the users and purchases tables. Treat users with no purchases as having zero spend, exclude users without a cohort, and use user_id as the tie-breaker.

Output

  1. One row per selected user, with columns cohort, user_id, total_spend, and user_rank.
  2. Include no more than three users per cohort, ordered by cohort, total_spend descending, and user_id ascending.

Schema

users
ColumnTypeDescription
user_idPKINTUnique user identifier
cohortVARCHAR(20)Cohort identifier assigned to the user
purchases
ColumnTypeDescription
purchase_idPKINTUnique purchase identifier
user_idINTUser associated with the purchase
amountNUMERIC(10,2)Purchase amount
Tablesuserspurchases
Your solutionPostgreSQL
You need to log in / sign up to run or submit.
Run a query to see results