[英]Find total duration (in minutes) between multiple rows with overlaps
I have the following table:我有下表:
start end
('19:48:43', '21:12:43')
('21:16:36', '21:17:36')
('21:19:22', '21:46:22')
('21:22:41', '22:03:41')
('21:23:29', '22:04:29')
And I need to know the total time (in minutes) between start
and end
taking into account overlaps.考虑到重叠,我需要知道
start
和end
之间的总时间(以分钟为单位)。 Given the above table, the computation would look like this:鉴于上表,计算将如下所示:
end
- start
= 84 minutesend
- start
= 84 分钟end
- start
= 1 minuteend
- start
= 1 分钟end
of row 5 and start
of row 3, which is 45 minutesend
和第 3 行的start
之间的差,即 45 分钟total = 84 + 1 + 45 = 130 minutes总计 = 84 + 1 + 45 = 130 分钟
I'm using SQLite.我正在使用 SQLite。 So far I haven't been able to arrive at any solution.
到目前为止,我还没有找到任何解决方案。
With a LEFT
join of 2 copies of the table to the table itself and aggregation:使用表的 2 个副本到表本身和聚合的
LEFT
连接:
WITH cte AS (
SELECT DISTINCT
COALESCE(MIN(ts.start), t.start) start,
COALESCE(MAX(te.end), t.end) end
FROM tablename t
LEFT JOIN tablename ts ON t.start BETWEEN ts.start AND ts.end
LEFT JOIN tablename te ON t.end BETWEEN te.start AND te.end
GROUP BY t.start, t.end
)
SELECT SUM(strftime('%s', end) - strftime('%s', start)) / 60 total
FROM cte
Or simpler:或更简单:
WITH cte AS (
SELECT DISTINCT
COALESCE(
(SELECT MIN(t2.start)
FROM tablename t2
WHERE t1.start BETWEEN t2.start AND t2.end), t1.start) start,
COALESCE(
(SELECT MAX(t2.end)
FROM tablename t2
WHERE t1.end BETWEEN t2.start AND t2.end), t1.start) end
FROM tablename t1
)
SELECT SUM(strftime('%s', end) - strftime('%s', start)) / 60 total
FROM cte
See the demo .请参阅演示。
Results:结果:
total![]() |
---|
130 ![]() |
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.