Encounter journey with dwell between milestones
Uses LEAD to compute minutes between consecutive operational events; surfaces longest intra-visit gaps per encounter.
-- Patient flow: time between consecutive ED events
WITH ordered_events AS (
SELECT
encounter_id,
event_type,
event_ts,
LEAD(event_ts) OVER (
PARTITION BY encounter_id ORDER BY event_ts, event_id
) AS next_ts
FROM curated.flow_events
WHERE event_ts IS NOT NULL
)
SELECT
encounter_id,
event_type,
TIMESTAMPDIFF(MINUTE, event_ts, next_ts) AS dwell_minutes_until_next
FROM ordered_events
WHERE next_ts IS NOT NULL
ORDER BY encounter_id, event_ts
LIMIT 500;