Sessionize Clicks With Lag

Split event streams into sessions: LAG measures the gap since the previous click, a flag marks 30-minute gaps, and a running SUM assigns session numbers.

SqlData Fetching

Code

snippet
WITH clicks(user_id, clicked_at) AS (
    VALUES
        (7, timestamptz '2026-06-01 09:00:00'),
        (7, timestamptz '2026-06-01 09:04:00'),
        (7, timestamptz '2026-06-01 09:45:00'),
        (7, timestamptz '2026-06-01 09:47:00'),
        (8, timestamptz '2026-06-01 10:00:00')
),
-- 与上一次点击的间隔:每次会话的第一条没有上一行,LAG 给 NULL
marked AS (
    SELECT
        user_id,
        clicked_at,
        clicked_at - LAG(clicked_at) OVER (PARTITION BY user_id ORDER BY clicked_at) AS gap
    FROM clicks
),
-- 间隔超过 30 分钟视为新会话:布尔标志再累加,就得到会话编号
numbered AS (
    SELECT
        user_id,
        clicked_at,
        SUM(CASE WHEN gap IS NULL OR gap > interval '30 minutes' THEN 1 ELSE 0 END)
            OVER (PARTITION BY user_id ORDER BY clicked_at) AS session_no
    FROM marked
)
SELECT
    user_id,
    session_no,
    MIN(clicked_at) AS started_at,
    MAX(clicked_at) AS ended_at,
    COUNT(*)        AS clicks
FROM numbered
GROUP BY user_id, session_no
ORDER BY user_id, session_no;

How it works

At its core this is a single SELECT statement against clicks, marked and numbered.

Mechanically, the statements are built from: a CTE (WITH … AS) that names an intermediate result before the main query; COUNT, SUM, MIN, MAX aggregation; a GROUP BY that collapses matching rows into one output row per group; 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.

Putting it to use

The clicks table is the working surface here.

Interactive Tools for This Topic

FAQ

Which tables or CTEs does it reference?
`clicks`, `marked`, `numbered` — referenced directly, no join needed.