Moving MAX
and MIN
could be a good fit here:
WITH sample_table AS (
SELECT TIMESTAMP("2021-01-15 20:27:59") timestamp, "unresolved" event_name UNION ALL
SELECT TIMESTAMP("2021-01-16 03:02:46"), "message" UNION ALL
SELECT TIMESTAMP("2021-01-20 19:31:37"), "resolved" UNION ALL
SELECT TIMESTAMP("2021-01-21 00:13:43"), "pending" UNION ALL
SELECT TIMESTAMP("2021-01-23 23:38:46"), "resolved" UNION ALL
SELECT TIMESTAMP("2021-01-24 00:38:17"), "message" UNION ALL
SELECT TIMESTAMP("2021-01-24 00:42:31"), "unresolved" UNION ALL
SELECT TIMESTAMP("2021-01-24 02:19:44"), "resolved" UNION ALL
SELECT TIMESTAMP("2021-01-25 15:55:50"), "message" UNION ALL
SELECT TIMESTAMP("2021-01-25 15:59:55"), "unresolved"
)
SELECT
*,
MAX(IF(prev_event='resolved' OR prev_event IS NULL, timestamp, NULL)) OVER (ORDER BY timestamp ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS start_time,
MIN(IF(event_name='resolved', timestamp, NULL)) OVER (ORDER BY timestamp ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING) AS resolved_time,
FROM (
SELECT
*,
LAG(event_name) OVER (ORDER BY timestamp) as prev_event,
FROM sample_table
)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…