LAG Turns Rows Into Day Gaps
Measure the elapsed days between consecutive visits with LAG and a date difference, converting row order into per-user inter-event gaps.
Code
SELECT
user_id,
visit_date,
LAG(visit_date) OVER (PARTITION BY user_id ORDER BY visit_date)
AS previous_visit,
visit_date
- LAG(visit_date) OVER (PARTITION BY user_id ORDER BY visit_date)
AS gap_days,
-- 首次访问没有前一行:LAG 返回 NULL,用 IS NULL 识别而不是 = NULL
CASE
WHEN LAG(visit_date) OVER (PARTITION BY user_id ORDER BY visit_date)
IS NULL THEN 'first visit'
WHEN visit_date - LAG(visit_date)
OVER (PARTITION BY user_id ORDER BY visit_date) <= 7
THEN 'returning within a week'
ELSE 'lapsed'
END AS cohort_label
FROM visits
ORDER BY user_id, visit_date;How it works
What runs is SELECT, with visits as the object involved.
What the statements actually assemble: a window function (OVER (…)) computing values across rows without collapsing them; an ORDER BY that fixes the output order.
Points of care
- Window functions evaluate after
WHERE/GROUP BY, so filtering on their output in the same-levelWHEREwill not work — use an outer query or a CTE.
Using it
Run the statement against the visits table.
Interactive Tools for This Topic
SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.SQL FormatterReformat SQL by uppercasing reserved words and breaking lines before SELECT, FROM, WHERE, and other clauses.
FAQ
- Which tables does this file reference?
- `visits`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.