Træk 30 minutter fra slutningen (eller starten) af hvert tidsinterval. Fortsæt derefter som beskrevet i mit referencede "enkle" svar (justerer de 30 min i den rigtige retning overalt). Områder, der er kortere end 30 minutter, elimineres a priori - hvilket giver mening, da de aldrig kan være en del af en 30 minutters periode med kontinuerlig overlapning. Gør også forespørgslen hurtigere.
Beregner for alle dage i oktober 2019 (eksempelområde):
WITH range AS (SELECT timestamp '2019-10-01' AS start_ts -- incl. lower bound
, timestamp '2019-11-01' AS end_ts) -- excl. upper bound
, cte AS (
SELECT userid, starttime
-- default to current timestamp if NULL
, COALESCE(endtime, localtimestamp) - interval '30 min' AS endtime
FROM usersessions, range r
WHERE starttime < r.end_ts -- count overlaps *starting* in outer time range
AND (endtime >= r.start_ts + interval '30 min' OR endtime IS NULL)
)
, ct AS (
SELECT ts, sum(ct) OVER (ORDER BY ts, ct) AS session_ct
FROM (
SELECT endtime AS ts, -1 AS ct FROM cte
UNION ALL
SELECT starttime , +1 FROM cte
) sub
)
SELECT ts::date, max(session_ct) AS max_concurrent_sessions
FROM ct, range r
WHERE ts >= r.start_ts
AND ts < r.end_ts -- crop outer time range
GROUP BY ts::date
ORDER BY 1;
db<>fiddle her
Vær opmærksom på, at LOCALTIMESTAMP
afhænger af tidszonen for den aktuelle session. Overvej at bruge timestamptz i din tabel og CURRENT_TIMESTAMP
i stedet. Se: