简体   繁体   English

查找重叠的多行之间的总持续时间(以分钟为单位)

[英]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.考虑到重叠,我需要知道startend之间的总时间(以分钟为单位)。 Given the above table, the computation would look like this:鉴于上表,计算将如下所示:

  • row 1's interval doesn't overlap with any other, so we calculate end - start = 84 minutes第 1 行的时间间隔不与任何其他时间重叠,因此我们计算end - start = 84 分钟
  • row 2's interval doesn't overlap with any other, so we calculate end - start = 1 minute第 2 行的时间间隔不与任何其他时间重叠,因此我们计算end - start = 1 分钟
  • row 3, 4, 5's intervals are overlapping, so we calculate the difference between end of row 5 and start of row 3, which is 45 minutes第 3、4、5 行的间隔是重叠的,所以我们计算第 5 行的end和第 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 130

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM