KatInterview

Rolling Week Averages with Calendar-Based Windows

SQL & DataAuto-graded
MediumAuto-gradedSQL & Datawindow-functionsdate-arithmeticaggregation

Last updated

Calculate a 7-day moving average for each date using calendar intervals, not row counts, handling gaps and NULL values correctly.

You are given a table of daily observations. Write a single PostgreSQL query to compute a rolling average over each date and the six preceding calendar days.

Table Schema

observations

ColumnTypeNotes
observation_datedateEach date appears at most once
readingnumericDaily measurement; can be NULL

Requirements

For each observation_date in the table, compute the mean of all non-NULL reading values whose observation_date falls within the 7-day calendar window ending on that date (inclusive of both boundaries).

Return two columns:

  • observation_date
  • avg_reading rounded to two decimal places

Rules

  • The window spans exactly seven calendar days: the target date and the six days before it.
  • Missing dates do not shift the window backward; they simply contribute no data.
  • NULL readings are excluded from the average calculation.
  • Include all input dates in the output, even if their window contains only NULLs or they are the earliest dates with fewer than seven days of history.
  • Sort results by observation_date in ascending order.

Example

Given:

observation_datereading
2024-02-01100
2024-02-02NULL
2024-02-04120
2024-02-08140

Expected output:

observation_dateavg_reading
2024-02-01100.00
2024-02-02100.00
2024-02-04110.00
2024-02-08130.00

For 2024-02-08, the window [2024-02-02, 2024-02-08] contains rows for 02-02, 02-04, and 02-08. Only 02-04 and 02-08 have non-NULL readings, so the average is (120 + 140) / 2 = 130.00.

Hints

Hint 1

The window is defined by date values, not by row positions. A gap in the data means fewer rows contribute to that window.

Hint 2

PostgreSQL window functions support RANGE frames with INTERVAL offsets for time-based windows.

Hint 3

If your SQL dialect lacks interval-based RANGE frames, a self-join with a BETWEEN condition on dates achieves the same result.