Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Three-Month Moving Averages by User

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

Your question is Three-Month Moving Averages by User. 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

Arity analyzes monthly mileage from connected-vehicle telemetry to support driver risk and usage insights. Write a PostgreSQL query that calculates a running three-month moving average of mileage for each active driver.

Requirements

  1. Include only drivers whose is_active value is TRUE.
  2. Return the driver ID, calendar month, reported mileage, and moving average.
  3. Partition calculations by user_id and order each driver's records chronologically.
  4. Use the current month and up to the two preceding monthly records, rounding the average to two decimal places. NULL mileage values should be ignored by AVG.

Assume arity_monthly_mileage contains at most one row per driver per calendar month.

Schema

arity_users
ColumnTypeDescription
user_idPKINTEGERUnique driver identifier
user_nameVARCHAR(100)Driver display name
is_activeBOOLEANWhether the driver is currently active
arity_monthly_mileage
ColumnTypeDescription
mileage_idPKINTEGERUnique mileage record identifier
user_idINTEGERReferences arity_users.user_id
month_startDATEFirst calendar day of the measurement month
miles_drivenNUMERIC(10,1)Total miles driven during the month
Tablesarity_usersarity_monthly_mileage
Your solutionPostgreSQL
You need to log in / sign up to run or submit.
Run a query to see results