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.

SqlData Integrity

Code

snippet
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-level WHERE will not work — use an outer query or a CTE.

Using it

Run the statement against the visits table.

Interactive Tools for This Topic

FAQ

Which tables does this file reference?
`visits`.