Status Transition Count With Lag

Count real status changes per ticket with LAG plus IS DISTINCT FROM, so repeated heartbeats in the same state never inflate the transition total.

SqlData Integrity

Code

snippet
CREATE TABLE ticket_events (
    ticket_id int NOT NULL,
    taken_at  timestamptz NOT NULL,
    status    text NOT NULL
);

INSERT INTO ticket_events VALUES
    (1, '2026-01-01 09:00+00', 'open'),
    (1, '2026-01-01 10:00+00', 'open'),         -- 同状态心跳,不计转变
    (1, '2026-01-01 11:00+00', 'in_progress'),
    (1, '2026-01-01 12:00+00', 'done'),
    (1, '2026-01-01 13:00+00', 'in_progress'),  -- 回退也计一次
    (1, '2026-01-01 14:00+00', 'done');

-- LAG 取上一行状态;IS DISTINCT FROM 同时处理 NULL 与值比较
WITH sequenced AS (
    SELECT ticket_id, status,
           LAG(status) OVER (PARTITION BY ticket_id ORDER BY taken_at) AS prev_status
    FROM ticket_events
)
SELECT ticket_id,
       COUNT(*) FILTER (WHERE prev_status IS NOT NULL
                        AND prev_status IS DISTINCT FROM status) AS transitions
FROM sequenced
GROUP BY ticket_id;

How it works

What runs here is SELECT / INSERT / CREATE — ticket_events, status and sequenced are the objects involved.

What the statements actually assemble: a CTE (WITH … AS) that names an intermediate result before the main query; a WHERE clause filtering the rows one statement applies to; COUNT 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; a DISTINCT qualifier that collapses duplicate rows; NOT NULL qualifiers on the required columns.

Caveats

  • 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 ticket_events table.

Key statements

INSERT INTO ticket_events VALUES
    (1, '2026-01-01 09:00+00', 'open'),
    (1, '2026-01-01 10:00+00', 'open'),         -- 同状态心跳,不计转变
    (1, '2026-01-01 11:00+00', 'in_progress'),
    (1, '2026-01-01 12:00+00', 'done'),
    (1, '2026-01-01 13:00+00', 'in_progress'),  -- 回退也计一次
    (1, '2026-01-01 14:00+00', 'done');
CREATE TABLE ticket_events (
    ticket_id int NOT NULL,
    taken_at  timestamptz NOT NULL,
    status    text NOT NULL
);

Interactive Tools for This Topic

FAQ

Which tables does this file reference?
The references are `ticket_events`, `status`, `sequenced`.