Rolling Week Averages with Calendar-Based Windows
SQL & DataAuto-gradedLast 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
| Column | Type | Notes |
|---|---|---|
| observation_date | date | Each date appears at most once |
| reading | numeric | Daily 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_dateavg_readingrounded 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_datein ascending order.
Example
Given:
| observation_date | reading |
|---|---|
| 2024-02-01 | 100 |
| 2024-02-02 | NULL |
| 2024-02-04 | 120 |
| 2024-02-08 | 140 |
Expected output:
| observation_date | avg_reading |
|---|---|
| 2024-02-01 | 100.00 |
| 2024-02-02 | 100.00 |
| 2024-02-04 | 110.00 |
| 2024-02-08 | 130.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.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core challenge is distinguishing between row-based and date-based windows. A naive approach using ROWS BETWEEN 6 PRECEDING AND CURRENT ROW treats the window as the last seven physical rows. When dates are missing, this pulls in observations from far earlier than the intended seven-day span.
The correct interpretation is a calendar window: for each date d, average all readings where observation_date is in [d - 6 days, d]. PostgreSQL supports this directly with a RANGE frame using an interval offset.
SQL Solution (Window Function)
SELECT
observation_date,
ROUND(
AVG(reading) OVER (
ORDER BY observation_date
RANGE BETWEEN INTERVAL '6 days' PRECEDING AND CURRENT ROW
),
2
) AS avg_reading
FROM observations
ORDER BY observation_date;
How it works:
RANGE BETWEEN INTERVAL '6 days' PRECEDING AND CURRENT ROWdefines the frame by comparing theORDER BYcolumn values, not row indices.- For each row with
observation_date = d, the frame includes all rows whereobservation_dateis betweend - 6anddinclusive. AVG(reading)automatically ignores NULL values in both numerator and denominator.ROUND(..., 2)formats the result to two decimal places.
SQL Solution (Self-Join Alternative)
For databases without interval-based RANGE frames:
SELECT
d.observation_date,
ROUND(AVG(w.reading), 2) AS avg_reading
FROM observations d
LEFT JOIN observations w
ON w.observation_date BETWEEN d.observation_date - 6 AND d.observation_date
GROUP BY d.observation_date
ORDER BY d.observation_date;
How it works:
- The outer query iterates over each date
d. - The join matches all rows
wwhose date falls in[d - 6, d]. - In PostgreSQL,
date - integersubtracts days, sod.observation_date - 6is exactly six days earlier. GROUP BY d.observation_dateaggregates each date's window into one row.- The
LEFT JOINensures every input date appears in the output, even if no rows match the join condition (though at minimum, each date matches itself).
Why This Is Correct
Calendar semantics: Each window contains exactly the rows within a seven-calendar-day span. A missing date simply means fewer rows contribute.
NULL handling: AVG computes the mean of non-NULL values only. If a window contains [100, NULL, 120], the result is 110, not 73.33.
Partial windows: Early dates naturally have shorter windows. The first date averages only itself; the second averages at most two dates, and so on.
No filtering: Every input date produces an output row. A window with all NULLs yields NULL for avg_reading, but the date still appears.
Rounding: ROUND(numeric, 2) uses exact arithmetic and rounds half away from zero, matching standard rounding rules.
Complexity
- Window function version: Sorting by
observation_dateis O(n log n) unless an index provides the order. Frame computation is O(n) because the window slides incrementally. Total: O(n log n) time, O(n) space. - Self-join version: Each date matches at most seven rows (dates are unique). With an index on
observation_date, this is O(n log n). Without an index, a nested-loop scan degrades to O(n²).
Edge Cases
| Scenario | Behavior |
|---|---|
| Gap of multiple days | Only dates actually present in [d-6, d] contribute |
| All readings NULL in window | avg_reading is NULL; date still appears |
| Current date NULL, past dates non-NULL | Average of the non-NULL past readings |
| First date in table | Window contains only that date; average is its own reading (or NULL) |
| Gap of 7+ days before a date | Window contains only the current date |
| Empty input table | Empty result set |
Example with gaps:
| observation_date | reading | Window dates | avg_reading |
|---|---|---|---|
| 2024-03-01 | 50 | 03-01 | 50.00 |
| 2024-03-03 | NULL | 03-01, 03-03 | 50.00 |
| 2024-03-05 | 60 | 03-01, 03-03, 03-05 | 55.00 |
| 2024-03-12 | 70 | 03-05, 03-12 | 65.00 |
For 03-12, the window [03-06, 03-12] includes only 03-12 itself and 03-05 (which falls within the range). Dates 03-01 and 03-03 are outside the window.
Common Mistakes
Using ROWS BETWEEN 6 PRECEDING: This counts physical rows, not calendar days. With gaps, it reaches too far back.
Forgetting NULL handling: Explicitly filtering WHERE reading IS NOT NULL before the window calculation removes dates with NULL readings from the output entirely, violating the requirement to include all dates.
Generating a full calendar: Using generate_series to create all dates in a range is unnecessary and can introduce dates not in the input.
Incorrect rounding: Using CAST(... AS DECIMAL(10,2)) truncates rather than rounding. Use ROUND explicitly.
What Interviewers Expect
- Immediate recognition that
ROWSvsRANGEis the key distinction. - Explanation of how gaps affect the window under each approach.
- Knowledge that
AVGinherently ignores NULLs. - A fallback method (self-join or correlated subquery) for databases without interval
RANGEsupport. - Awareness that over-engineering (calendar generation, extra CTEs) adds complexity without benefit.