請嘗試以下。我認爲這不正是你問
正如你所看到的 - 我加在你的例子一個條目,使其一點點辣:O)
WITH YourTable AS (
SELECT TIMESTAMP '2016-01-01 00:00:00' AS start_time, TIMESTAMP '2016-01-01 08:59:59' AS end_time, 1 AS value UNION ALL
SELECT TIMESTAMP '2016-01-01 06:00:00' AS start_time, TIMESTAMP '2016-01-01 14:59:59' AS end_time, 2 AS value UNION ALL
SELECT TIMESTAMP '2016-01-01 12:00:00' AS start_time, TIMESTAMP '2016-01-01 17:59:59' AS end_time, 1.5 AS value UNION ALL
SELECT TIMESTAMP '2016-01-01 03:00:00' AS start_time, TIMESTAMP '2016-01-01 17:59:59' AS end_time, 3 AS value UNION ALL
SELECT TIMESTAMP '2016-01-01 12:30:00' AS start_time, TIMESTAMP '2016-01-01 12:40:59' AS end_time, 1 AS value
),
Intervals AS (
SELECT iStart AS start_time, LEAD(iStart) OVER(ORDER BY iStart) AS end_time
FROM (
SELECT DISTINCT iStart FROM (
SELECT start_time AS iStart FROM YourTable UNION ALL
SELECT end_time AS iStart FROM YourTable)
)
),
Intervals_Mins AS (
SELECT b.start_time, b.end_time, MIN(value) AS min_value
FROM YourTable AS a
JOIN Intervals AS b
ON b.start_time BETWEEN a.start_time AND a.end_time
AND b.end_time BETWEEN a.start_time AND a.end_time
GROUP BY b.start_time, b.end_time
),
Intervals_Group AS (
SELECT start_time, end_time, min_value, IFNULL(SUM(flag) OVER(PARTITION BY CAST(min_value AS STRING) ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING), 0) AS time_group
FROM (
SELECT start_time, end_time, min_value, IF(end_time = LEAD(start_time) OVER(PARTITION BY CAST(min_value AS STRING) ORDER BY start_time), 0, 1) AS flag
FROM Intervals_Mins
)
)
SELECT MIN(start_time) AS start_time, MAX(end_time) AS end_time, min_value
FROM Intervals_Group
GROUP BY min_value, time_group
-- ORDER BY start_time
這是一個非常困難的問題。 –
@戈登林諾夫 - 同意,比這裏的常見問題複雜一點:o) –