关于sql统计时间重叠和时间不重叠的问题
我们在开发过程中总会遇到这样的情况,一行数据中,有id、组、开始时间、结束时间。但是开始时间和结束时间肯定会出现时间重叠问题,比如说下面这种情况。
我们先找出时间重叠的公式:
可以发现:
公式如下:
a.alarm_type_id = b.alarm_type_id AND
a.start_time <= b.stop_time AND
a.stop_time >= b.start_time AND
a.id <> b.id
详细的sql语句:
selectDISTINCT b.*
from`time_table` a,`time_table` b
wherea.id <> b.id ANDa.alarm_type_id = b.alarm_type_id ANDa.start_time <= b.stop_time ANDa.stop_time >= b.start_time
查询出时间不重叠的数据:
select *
from time_table a
where a.id not in (select DISTINCT b.id from `time_table` a,`time_table` b where a.id <> b.id ANDa.alarm_type_id = b.alarm_type_id ANDa.start_time <= b.stop_time ANDa.stop_time >= b.start_time );
统计重叠时间的方法,我们可以先分组,然后获取分组后的数据的最小时间和最大时间,之后做差就能求出时间和。
selectalarm_type_id, UNIX_TIMESTAMP(MAX(k1.stop_time))-UNIX_TIMESTAMP(MIN(k1.start_time))
from (selectDISTINCT b.*from`time_table` a,`time_table` bWHEREa.id <> b.id ANDa.alarm_type_id = b.alarm_type_id ANDa.start_time <= b.stop_time ANDa.stop_time >= b.start_time
) k1 group by k1.alarm_type_id;
统计不重叠时间的方法。
select alarm_type_id, sum(UNIX_TIMESTAMP(stop_time) - UNIX_TIMESTAMP(start_time)) time_sum
from (select *from time_table awhere a.id not in (select DISTINCT b.id from `time_table` a,`time_table` b where a.id <> b.id ANDa.alarm_type_id = b.alarm_type_id ANDa.start_time <= b.stop_time ANDa.stop_time >= b.start_time )
) k2 group by alarm_type_id;
接下来可以直接整合统计,没什么难度,直接两条语句连起来。然后分组查询,进行sum。
问题:
会出现存在本周第一天和上周最后一天存在跨天的情况,可以直接截取进行统计。