Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Compute 7-Day Rolling Revenue

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

Your question is Compute 7-Day Rolling Revenue. Start with the requirements and the one table 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

Lynx Analytics needs a time-based revenue feature for user behavior analysis. Write a PostgreSQL query that aggregates event revenue by user and calendar day, then calculates each user's trailing 7-day revenue for every day on which that user has an event.

The window must include the current calendar day and the six preceding calendar days. Treat a NULL revenue value as zero, and retain events whose user_id is NULL as a separate partition.

Requirements

  1. Aggregate multiple events for the same user and calendar day before applying the rolling calculation.
  2. Return user_id, event_day, daily_revenue, and rolling_7_day_revenue.
  3. Use a time-based window frame rather than a fixed number of rows, because users may have gaps between active days.
  4. Order the final results by user_id ascending with NULL users first, then by event_day ascending.

Schema

events
ColumnTypeDescription
event_idPKINTUnique event identifier
user_idINTUser associated with the event
event_timeTIMESTAMPTZUTC timestamp when the event occurred
revenueNUMERIC(12,2)Revenue attributed to the event
Tablesevents
Your solutionPostgreSQL
You need to log in / sign up to run or submit.
Run a query to see results