Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

SQL Running Totals and Averages

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

Your question is SQL Running Totals and Averages. 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

Avathon's industrial monitoring system stores sensor readings for registered machines. Write a PostgreSQL query that summarizes readings for active machines during March 1 through March 10, 2025.

Requirements

  1. Join the machine registry to sensor readings and include only active machines in the requested date range.
  2. Aggregate multiple readings from the same machine and date into daily totals, counts, and averages.
  3. Calculate a chronological running total of readings for each machine.
  4. Calculate a trailing seven-calendar-day average, inclusive of the current date. Treat missing and NULL readings as unavailable rather than zero for the average.

Use RANGE BETWEEN INTERVAL '6 days' PRECEDING AND CURRENT ROW for the inclusive seven-day window. Preserve dates containing only NULL readings so the running total remains unchanged and the moving average excludes those NULL values.

Schema

machines
ColumnTypeDescription
machine_idPKINTEGERUnique machine identifier
machine_codeVARCHAR(20)Avathon machine code
asset_nameVARCHAR(100)Human-readable asset name
statusVARCHAR(20)Current machine status
sensor_readings
ColumnTypeDescription
reading_idPKINTEGERUnique sensor reading identifier
machine_idINTEGERMachine that produced the reading
reading_dateDATECalendar date of the reading
reading_valueNUMERIC(10,2)Sensor measurement
Tablesmachinessensor_readings
Your solutionPostgreSQL
You need to log in / sign up to run or submit.
Run a query to see results