简体   繁体   English

查找重叠时间的计数

[英]Finding count of overlapping times

I have a postgres database that contains: 我有一个postgres数据库,其中包含:

position (which has values 1-10), starttime , endtime , and status . position (其具有值1-10), starttimeendtime ,和status Status is either "on" or "off". 状态为“开”或“关”。 The database lists the start and stop times of when a machine position is "on" or "off", and that machine has 10 "positions". 该数据库列出了机器位置为“开”或“关”且该机器具有10个“位置”的开始和停止时间。

I am trying to find the best way to count the how much time accrues where all 10 positions have the status off at the same time. 我试图找到最好的方法来计算所有10个职位同时处于关闭状态的时间。

I don't claim that this is the best solution, but it's one of them. 我并不是说这是最好的解决方案,但这是其中之一。 The idea is to select only position 1 and join with the table itself where the times overlap and position is not 1. If we find 9 distinct position values, then we found one occurance where all positions are off. 这个想法是只选择位置1,然后与时间重叠且位置不为1的表本身连接。如果我们找到9个不同的位置值,则发现所有位置均关闭的一种情况。

SELECT
  t.machine_id,
  COUNT(*) occurances
FROM (
  SELECT
    t1.machine_id,
    t1.starttime,
    COUNT(DISTINCT t2.position) c
  FROM
    yourTable t1 INNER JOIN
    yourTable t2 ON
    t2.machine_id = t1.machine_id AND
    t2.status = 'off' AND
    t2.position <> 1 AND
    (t2.starttime BETWEEN t1.starttime AND t1.endtime OR  -- those 3 lines check if the
    t2.endtime BETWEEN t1.starttime AND t1.endtime OR  -- times are overlapping
    (t2.starttime < t1.starttime AND t2.endtime > t1.endtime))
  WHERE
    t1.status = 'off' AND
    t1.position = 1
  GROUP BY
    t1.machine_id,
    t1.starttime
  ) t
WHERE
  t.c = 9
GROUP BY
  t.machine_id
;

The results may vary depending on what position you select for t1 . 结果可能会有所不同,具体取决于您为t1选择的位置。 Because if one position takes very short and another a long time then you might count the same overlap several times (also depends on the other position times). 因为如果一个职位花费的时间很短而另一个职位花费的时间很长,那么您可能会多次计算相同的重叠(也取决于其他职位的时间)。 So choose the position which takes the longest time and not just 1. 因此,选择花费时间最长的职位,而不只是1。

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

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