查找记录中的重叠时间并在SQL中设置组ID

问题描述 投票:0回答:1

示例:

ID  START_TIME  END_TIME    GROUP_ID
100 10:00   12:00   1
100 10:15   12:30   1
100 12:15   12:45   1
100 13:00   14:00   2
200 10:15   10:30   3

对于给定的ID,我想查找其任何间隔是否重叠,则对应的记录属于同一组,因此应具有相同的group_id。当A的start_time和/或end_time在B的start_timeend_time之间时,一条记录A与另一条记录B重叠。

在示例中,ID = 100有四个间隔。前三个重叠=>第二个记录与第一个重叠(10:15的start_time在10:00到12:00的start_timeend_time之间),第三个与第二个重叠( 12:15的start_time在10:15至12:30的start_timeend_time之间。因此,它们都具有相同的group_id为1。ID = 100的第四个间隔不与该ID内的任何其他间隔重叠,因此它成为带有新的group_id的自己的组。 ]。最后一条记录具有完全不同的ID,因此它也以新的group_id开始了第三组。

解决此问题的最佳方法是什么?

例如:ID START_TIME END_TIME GROUP_ID 100 10:00 12:00 1 100 10:15 12:30 1100 12:15 12:45 1 100 13:00 14:00 2 200 10:15 10:30 3给定ID,我想查找是否有...

mysql sql time group-by overlapping
1个回答
0
投票

您可以使用exists

select t.*
from t
where exists (select 1
              from t t2
              where t2.group_id = t.group_id and
                    t2.start_time < t.end_time and
                    t2.end_time > t.start_time
             );
© www.soinside.com 2019 - 2024. All rights reserved.