Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Write Rolling Average SQL

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

Your question is Write Rolling Average SQL. 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

Engie Impact uses customer energy data to monitor consumption patterns and support operational planning. Write a PostgreSQL query that calculates a 7-day rolling average of daily energy usage for each customer.

The rolling average should average recorded daily totals within the current date and the preceding six calendar days. Days without readings are not included as zero-usage days.

Requirements

  1. Aggregate multiple readings for the same customer and date into one daily usage total.
  2. Calculate the rolling average separately for each customer using a window function and a six-day preceding date range.
  3. Include the customer ID, customer name, usage date, daily usage in kWh, and rolling average in kWh.
  4. Exclude readings with no matching customer, while allowing NULL usage values to be ignored by the aggregate functions.
  5. Order the results by customer ID and usage date.

Schema

customers
ColumnTypeDescription
customer_idPKINTUnique customer identifier
customer_nameVARCHAR(100)Customer or account name
energy_usage
ColumnTypeDescription
reading_idPKINTUnique usage reading identifier
customer_idINTCustomer associated with the reading
usage_dateDATEDate of energy usage
usage_kwhNUMERIC(12,2)Energy consumed in kilowatt-hours
Tablescustomersenergy_usage
Your solutionPostgreSQL
You need to log in / sign up to run or submit.
Run a query to see results