Den særlige vanskelighed er ikke at gå glip af tidsintervallerne til den ydre tidsramme.
Forudsat at den næste række for et givet id
har altid den modsatte status.
Ved brug af kolonnenavnet ts
i stedet for recordTime
:
WITH span AS (
SELECT '2014-03-01 13:00'::timestamp AS s_from -- start of time range
, '2014-03-01 14:00'::timestamp AS s_to -- end of time range
)
, cte AS (
SELECT id, ts, status, s_to
, lead(ts, 1, s_from) OVER w AS span_start
, first_value(ts) OVER w AS last_ts
FROM span s
JOIN tbl t ON t.ts BETWEEN s.s_from AND s.s_to
WINDOW w AS (PARTITION BY id ORDER BY ts DESC)
)
SELECT id, sum(time_disconnected)::text AS total_disconnected
FROM (
SELECT id, ts - span_start AS time_disconnected
FROM cte
WHERE status = 'Connected'
UNION ALL
SELECT id, s_to - ts
FROM cte
WHERE status = 'Disconnected'
AND ts = last_ts
) sub
GROUP BY 1
ORDER BY 1;
Returnerer intervaller som anmodet.
Id'er uden indtastninger i det valgte tidsinterval vises ikke. Du bliver nødt til at forespørge dem yderligere.
SQL Fiddle.
Bemærk:Jeg caster den resulterende total_disconnected
til text
i violinen, fordi typen interval
vises i et forfærdeligt format.
Tilføj ID'er uden indtastning i den valgte tidsramme
Føj til forespørgslen ovenfor (før den endelige ORDER BY 1
):
...
UNION ALL
SELECT id, total_disconnected
FROM (
SELECT DISTINCT ON (id)
t.id, t.status, (s.s_to - s.s_from)::text AS total_disconnected
FROM span s
JOIN tbl t ON t.ts < s.s_from -- only from before time range
LEFT JOIN cte c USING (id)
WHERE c.id IS NULL -- not represented in selected time frame
ORDER BY t.id, t.ts DESC -- only the latest entry
) sub
WHERE status = 'Disconnected' -- only if disconnected
ORDER BY 1;
Nu kun id'er uden indtastninger i eller før det valgte tidsinterval vises ikke.