Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Window Functions for Running Totals

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

Your question is Window Functions for Running Totals. 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

NewMarket wants to evaluate user engagement by signup cohort. Write a PostgreSQL query that summarizes qualifying transactions by user and calendar month, calculates each user's cumulative spend, and ranks users within their signup cohort.

Requirements

  1. Derive cohort_month from users.signup_date and activity_month from transactions.transaction_date.
  2. Include only transactions on or after the user's signup date. Exclude transactions that cannot be matched to a user.
  3. Aggregate transaction amounts by user and activity month.
  4. Calculate a per-user running total ordered by activity month, and rank users within each cohort by total spend descending. Preserve ties with the same rank.
  5. Return one row per user and activity month, ordered by cohort, activity month, and user ID.

Schema

users
ColumnTypeDescription
user_idPKINTUnique NewMarket user identifier
user_nameVARCHAR(100)User display name
signup_dateDATEDate the user joined NewMarket
transactions
ColumnTypeDescription
transaction_idPKINTUnique transaction identifier
user_idINTUser associated with the transaction
transaction_dateDATEDate of the transaction
amountNUMERIC(10,2)Transaction amount
Tablesuserstransactions
Your solutionPostgreSQL
You need to log in / sign up to run or submit.
Run a query to see results