Peak Concurrent Visitors With Window Sums

Unpack session intervals into enter and leave events, then window-sum the deltas to find the moment with the most simultaneous visitors.

SqlData Integrity

Code

snippet
-- 会话区间:entered_at 进场,left_at 离场
CREATE TABLE visits (
    id         integer PRIMARY KEY,
    user_id    integer NOT NULL,
    entered_at timestamptz NOT NULL,
    left_at    timestamptz NOT NULL
);

INSERT INTO visits VALUES
    (1, 10, '2026-11-18 09:00+00', '2026-11-18 09:40+00'),
    (2, 11, '2026-11-18 09:20+00', '2026-11-18 10:10+00'),
    (3, 12, '2026-11-18 09:30+00', '2026-11-18 09:35+00'),
    (4, 13, '2026-11-18 10:05+00', '2026-11-18 10:30+00'),
    (5, 14, '2026-11-18 11:00+00', '2026-11-18 11:20+00');

-- peak concurrent visitors: +1 on enter, -1 on leave
WITH events AS (
    SELECT entered_at AS at_time,  1 AS delta FROM visits
    UNION ALL
    SELECT left_at    AS at_time, -1 AS delta FROM visits
),
timeline AS (
    -- 同一时刻先处理 -1 再处理 +1:离场与进场不重叠
    SELECT at_time,
           SUM(delta) OVER (ORDER BY at_time, delta) AS concurrent
    FROM events
)
SELECT at_time, concurrent
FROM timeline
ORDER BY concurrent DESC, at_time
LIMIT 1;

What the code does

Several statements share this file — SELECT / INSERT / CREATE, with visits, events and timeline among the objects involved.

The pieces that do the work: a CTE (WITH … AS) that names an intermediate result before the main query; SUM aggregation; a window function (OVER (…)) computing values across rows without collapsing them; an ORDER BY that fixes the output order; a row cap (LIMIT) bounding the result size; a UNION combining result sets from separate queries; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity.

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; the LIMIT keeps the probe cheap while you tune the predicates.

Key statements

INSERT INTO visits VALUES
    (1, 10, '2026-11-18 09:00+00', '2026-11-18 09:40+00'),
    (2, 11, '2026-11-18 09:20+00', '2026-11-18 10:10+00'),
    (3, 12, '2026-11-18 09:30+00', '2026-11-18 09:35+00'),
    (4, 13, '2026-11-18 10:05+00', '2026-11-18 10:30+00'),
    (5, 14, '2026-11-18 11:00+00', '2026-11-18 11:20+00');
CREATE TABLE visits (
    id         integer PRIMARY KEY,
    user_id    integer NOT NULL,
    entered_at timestamptz NOT NULL,
    left_at    timestamptz NOT NULL
);

Interactive Tools for This Topic

FAQ

Name the tables involved in this file.
`visits`, `events`, `timeline`.