Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started
SQL Window Functions Moving Average
00:00
5 left

SQL Window Functions Moving Average

MediumSQL · PostgreSQL

Problem

AArete's client analytics reporting workflow needs a smoother view of daily revenue from active client accounts. Write a PostgreSQL query that aggregates eligible transactions and calculates a rolling three-day average.

Requirements

  1. Join revenue_transactions to client_accounts and include only accounts with account_status = 'active'.
  2. Calculate daily_revenue, the total revenue for each transaction date.
  3. Calculate moving_avg_3_days: the average of the current date's revenue and the two preceding dates that have revenue (reporting dates, not calendar days). If fewer than three dates exist, average the available rows.
  4. Round moving_avg_3_days to two decimal places with ROUND(..., 2). Leave daily_revenue as the plain sum (amounts already have two decimals).
  5. Return revenue_date, daily_revenue, and moving_avg_3_days in ascending date order.

Schema

client_accounts
ColumnTypeDescription
account_idPKINTEGERUnique client account identifier
account_nameVARCHAR(100)Client account name
account_statusVARCHAR(20)Current account status
revenue_transactions
ColumnTypeDescription
transaction_idPKINTEGERUnique revenue transaction identifier
account_idINTEGERClient account associated with the transaction
revenue_dateDATEDate on which revenue was recorded
revenue_amountNUMERIC(12,2)Revenue amount for the transaction
Tablesclient_accountsrevenue_transactions
Interviewer

Your question is SQL Window Functions Moving Average. Start with the requirements and the two tables in the Question tab.

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.
CodePostgreSQL
You need to log in / sign up to run or submit.Ln 1
Run your query to see results here.