Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

SQL Window Functions Moving Average

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

Your question is SQL Window Functions Moving Average. 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

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 total revenue for each transaction date.
  3. Use a window function to calculate the average of the current day's revenue and the two preceding reporting dates. If fewer than three dates exist, average the available rows.
  4. Return results in ascending date order with daily revenue and the moving average rounded to two decimal places.

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
Your solutionPostgreSQL
You need to log in / sign up to run or submit.
Run a query to see results