The full answer
Starfire first decides what a missing day means, then picks the window that matches. A time-based window (RANGE BETWEEN INTERVAL 2 DAYS PRECEDING AND CURRENT ROW) already averages only the readings that fall in the last three days, whatever the gaps. If a missing day should count as zero, or should be visible as a row, she first builds a complete calendar with sequence() and joins the data to it.
Sample data: readings on 1, 2, 5 and 6 October; 3 and 4 October are missing.
1. A row-based window is the trap
AVG(value) OVER (ORDER BY reading_date ROWS BETWEEN 2 PRECEDING AND CURRENT ROW)
This averages the last three rows. On 5 October it would include 1 and 2 October, a week's span, because the rows for 3 and 4 do not exist. Only use it when every period is present.
2. A time-based window handles gaps correctly
SELECT reading_date, value,
AVG(value) OVER (ORDER BY reading_date
RANGE BETWEEN INTERVAL 2 DAYS PRECEDING AND CURRENT ROW) AS avg_3_days
FROM readings;
The frame is defined by dates, not row positions, so on 5 October it holds only the readings from 3 to 5 October, which is just 5 October. Result: 10, 15, 30, 35. Add COUNT(value) OVER (...) to show how many readings each average rests on, so a one-reading "average" is visible.
3. A full calendar, when missing days need rows or values
WITH bounds AS (
SELECT min(reading_date) AS first_day, max(reading_date) AS last_day FROM readings
),
days AS (
SELECT explode(sequence(first_day, last_day, INTERVAL 1 DAY)) AS day FROM bounds
),
filled AS (
SELECT d.day, r.value
FROM days d LEFT JOIN readings r ON r.reading_date = d.day
)
SELECT day, value,
AVG(value) OVER w AS avg_present_days,
AVG(coalesce(value, 0)) OVER w AS avg_missing_as_zero,
COUNT(value) OVER w AS days_with_data
FROM filled
WINDOW w AS (ORDER BY day ROWS BETWEEN 2 PRECEDING AND CURRENT ROW)
ORDER BY day;
Every day now has a row, so a row-based window equals a time-based one. AVG ignores NULL, so avg_present_days matches the RANGE result, while avg_missing_as_zero treats a missing day as zero (right for sales, wrong for a temperature sensor). Computing the bounds in their own step keeps explode out of the aggregate query. For many series, cross join the calendar with the list of series IDs and add PARTITION BY series_id to the window.
4. Carrying the last value forward
For readings that stay valid until the next one (a price, a stock level), fill each gap with the previous value:
coalesce(value, last_value(value, true) OVER (ORDER BY day ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW))
The true makes last_value skip NULLs.
Which to choose: RANGE when missing means no data; a calendar with zeros when missing means nothing happened; forward fill when missing means unchanged. Saying which one fits and why is what interviewers listen for. (These queries were run on Apache Spark 4.2 with the sample data above.)
Last updated 16 October 2026
Sources