Explain how to carry a value forward to fill gaps (LOCF / last-observation-carried-forward) using window functions in a time series.
Last updated
LOCF (last observation carried forward) fills NULL gaps with the most recent non-NULL value.
LAG()alone can't do it because it only looks back one row.Two-step trick: build a group id with
COUNT(value) OVER (ORDER BY ts)(increments only on real values), then takeMAX(value) OVER (PARTITION BY grp)to spread that value across the group.Partition per series (e.g. per sensor) to avoid leakage. Some engines offer a shortcut:
LAST_VALUE(... IGNORE NULLS).