Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

SQL Window Functions for Trends

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

Your question is SQL Window Functions for Trends. 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

Duke University research administrators need a monthly view of expenditures recorded for active research grants. Write a PostgreSQL query that summarizes expenditures from January through March 2025 and calculates running totals and moving averages for each grant.

Requirements

  1. Join grants to expenditures and include only active grants with expenditures in the requested date range.
  2. Aggregate multiple expenditure records into one row per grant and calendar month.
  3. Calculate a cumulative running total and a three-month moving average using window functions, ordered chronologically within each grant.
  4. Return results ordered by grant and month. Preserve NULL monthly totals when a month contains only NULL expenditure amounts.

Schema

grants
ColumnTypeDescription
grant_idPKINTEGERUnique research grant identifier
grant_nameVARCHAR(150)Research grant title
principal_investigatorVARCHAR(120)Principal investigator responsible for the grant
statusVARCHAR(20)Current grant status
grant_expenditures
ColumnTypeDescription
expenditure_idPKINTEGERUnique expenditure record identifier
grant_idINTEGERGrant associated with the expenditure
expenditure_dateDATEDate the expenditure was recorded
amountNUMERIC(12,2)Expenditure amount in US dollars
Tablesgrantsgrant_expenditures
Your solutionPostgreSQL
You need to log in / sign up to run or submit.
Run a query to see results