Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Window Functions for Purchase Rankings

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

Your question is Window Functions for Purchase Rankings. 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

Amazon’s analytics team wants to monitor how frequently customers purchase over time. Write a PostgreSQL query that summarizes completed purchases by user and calendar month, then uses window functions to calculate running averages and rank users by purchase frequency.

Requirements

  1. Consider only completed transactions from January 1 through March 31, 2024.
  2. Calculate each user’s monthly completed purchase count.
  3. Calculate the running average of monthly purchase counts for each user, ordered chronologically.
  4. Rank users by their total completed purchase count in descending order, using standard competition ranking.

Return one row per user-month with user_name, purchase_month, monthly_purchase_count, running_avg_purchase_frequency, total_purchases, and frequency_rank.

Schema

users
ColumnTypeDescription
user_idPKINTEGERUnique Amazon customer identifier
user_nameVARCHAR(100)Customer display name
transactions
ColumnTypeDescription
transaction_idPKBIGINTUnique transaction identifier
user_idINTEGERCustomer who made the transaction
purchased_atTIMESTAMPTransaction timestamp
statusVARCHAR(20)Transaction state
Tablesuserstransactions
Your solutionPostgreSQL
You need to log in / sign up to run or submit.
Run a query to see results