如何在MySQL中组合重叠的日期范围?

时间:2016-07-11 18:34:45

标签: mysql date-range

我有一张桌子“lessons_holidays”。它可以包含几个假日日期范围,即

"holiday_begin"    "holiday_end" 
2016-06-15         2016-06-15
2016-06-12         2016-06-16
2016-06-15         2016-06-19
2016-06-29         2016-06-29

如果日期范围重叠,我想合并每个条目。我需要这样的输出:

"holiday_begin"    "holiday_end" 
2016-06-12         2016-06-19
2016-06-29         2016-06-29

SQL:以下sql语句加载所有行。现在我被卡住了。

SELECT lh1.holiday_begin, lh1.holiday_end 
FROM local_lessons_holidays lh1 
WHERE lh1.holiday_impact = '1' AND
(DATE_FORMAT(lh1.holiday_begin, '%Y-%m') <= '2016-06' AND DATE_FORMAT(lh1.holiday_end, '%Y-%m') >= '2016-06') AND
lh1.uid = '1' 

1 个答案:

答案 0 :(得分:3)

这是一个难题,因为你使用MySQL而变得更难。这是一个想法。查找每个组中所有假期的开始日期。然后是&#34;开头&#34;的标志的累积总和。处理组。其余的只是聚合。

假设您没有重复记录,以下内容应该是您想要的:

select min(holiday_begin) as holiday_begin, max(holiday_end) as holiday_end
from (select lh.*, (@grp := @grp + group_flag) as grp
      from (select lh.*,
                   (case when not exists (select 1
                                          from lessons_holidays lh2
                                          where lh2.holiday_begin <= lh.holiday_end and
                                                lh2.holiday_end > lh.holiday_begin and
                                                (lh2.holiday_begin <> lh.holiday_begin or
                                                 lh2.holiday_end < lh.holiday_end)

                                         )
                         then 1 else 0
                    end) as group_flag
            from lessons_holidays lh
           ) lh cross join
           (select @grp := 0) params
      order by holiday_begin, holiday_end
    ) lh
group by grp;

如果您有重复项,只需在表格最里面的引用上使用select distinct

Here是一个SQL小提琴。

编辑:

此版本似乎效果更好:

select min(holiday_begin) as holiday_begin, max(holiday_end) as holiday_end
from (select lh.*, (@grp := @grp + group_flag) as grp
      from (select lh.*,
                   (case when not exists (select 1
                                          from lessons_holidays lh2
                                          where lh2.holiday_begin <= lh.holiday_begin and
                                                lh2.holiday_end > lh.holiday_begin and
                                                lh2.holiday_begin <> lh.holiday_begin and
                                                lh2.holiday_end <> lh.holiday_end
                                         )
                         then 1 else 0
                    end) as group_flag
            from lessons_holidays lh
           ) lh cross join
           (select @grp := 0) params
      order by holiday_begin, holiday_end
    ) lh
group by grp;

如图所示here