HAVING MAX的含义是什么(条件为0则1结束时为0)

时间:2019-10-02 20:37:42

标签: mysql mysql-8.0

我有一个表,其中包含id,start_time,end_time,如下所示:

id  start_time   end_time 
 1    10:00        12:00
 1    10:15        12:30
 1    12:15        12:45
 1    13:00        14:00
 2    10:15        10:30 

我正在尝试组合连续或相同的时间段,即将多个记录查询组合为每个ID的一个连续时间段记录。结果应该是这样的:

id  start_time   end_time 
 1    10:00        12:30
 1    13:00        14:00
 2    10:15        10:30

有一个有效的查询。但是我不明白拥有max(case ... end)= 0的含义。为什么这种情况可以过滤输出?为什么我们需要将表内部联接3次而不是两次?

select t4.id, t4.start_time as start, min(t4.end_time) as end
from (select t1.id, t1. start_time, t2.end_time 
      from t t1, t t2, t t3
      where t1. end_time <= t2. end_time
      and t1.id = t2.id
      group by t1.id, t1. start_time, t2. end_time
      having max(case when
                 (t1. start_time >t3. start_time and t1. start_time <=t3. end_time and t1.id=t3.id) or
                 (t2. end_time >=t3. start_time and t2. end_time <t3. end_time and t2.id=t3.id)
                 then 1 else 0 end)=0) t4
group by t4.id, t4. start_time

0 个答案:

没有答案