LAG LEAD Gap Fill Time Series
Detect missing intervals in time series with LAG over generated series, then backfill gaps by carrying the last known value forward.
Code
-- 用 generate_series 铺满时间轴,再左连接真实观测
WITH full_axis AS (
SELECT generate_series(
date_trunc('hour', '2026-10-21 00:00'::timestamp),
date_trunc('hour', '2026-10-21 12:00'::timestamp),
interval '1 hour'
) AS bucket
),
joined AS (
SELECT
f.bucket,
s.temperature,
LAG(s.temperature) OVER (ORDER BY f.bucket) AS prev_temp
FROM full_axis f
LEFT JOIN sensor_readings s
ON date_trunc('hour', s.read_at) = f.bucket
)
SELECT
bucket,
temperature,
COALESCE(
temperature,
prev_temp -- 缺失点沿用上一个已知值
) AS filled_temperature
FROM joined
ORDER BY bucket;
-- 只列出缺口清单:与前一个桶的间隔超过一格
WITH detected AS (
SELECT
bucket,
LAG(bucket) OVER (ORDER BY bucket) AS prev_bucket,
temperature
FROM joined_fillable
)
SELECT
prev_bucket AS gap_start,
bucket AS gap_end,
bucket - prev_bucket AS gap_width
FROM detected
WHERE prev_bucket IS NOT NULL
AND bucket - prev_bucket > interval '1 hour';Inside the snippet
Several statements share this file — SELECT, with full_axis, sensor_readings, joined, joined_fillable and detected among the objects involved.
Concretely, the SQL combines: a CTE (WITH … AS) that names an intermediate result before the main query; one JOIN combining rows across tables; a WHERE clause that narrows down the rows one statement touches; a window function (OVER (…)) calculating values across rows while every row stays visible; an ORDER BY that fixes the output order; NOT NULL qualifiers on the required columns.
What to watch for
- Window output exists only after grouping — filter it from an enclosing query, not the same one.
Putting it to use
Run the statement against the full_axis table.
Core lines
WITH detected AS (
SELECT
bucket,
LAG(bucket) OVER (ORDER BY bucket) AS prev_bucket,
temperature
FROM joined_fillable
)
SELECT
prev_bucket AS gap_start,
bucket AS gap_end,
bucket - prev_bucket AS gap_width
FROM detected
WHERE prev_bucket IS NOT NULL
AND bucket - prev_bucket > interval '1 hour';
Interactive Tools for This Topic
FAQ
- Which tables appear in this script?
- `full_axis`, `sensor_readings`, `joined`, `joined_fillable`, `detected` — joined via one JOIN clause.
Report a problem with this exampleOpens a pre-filled issue on GitHub.