如何将多个日期行转换为连续日期的日期范围?

How to convert multiple date rows into a date range of continuous dates?

id load_date
123 2021-03-01
123 2021-02-01
123 2021-01-01
123 2020-12-31
123 2020-11-13
123 2020-05-14
123 2020-04-16
123 2019-01-16

这些是我为某个特定成员准备的日期列表,我想将其转换为连续日期的日期范围(基于月份和年份)

预期结果:

Member_StartDate Member_TermDate
2019-01-16 2019-01-16
2020-04-16 2020-05-14
2020-11-13 2021-03-01

我想要使用 sql qry 得到 mysql5.7 的结果 如有任何帮助,我们将不胜感激。

这是 8.0 中相当直接的分组

select patient_id,  min(load_date) s,  max(load_date) e
from (
   select t.*, 
      sum(seq) over(partition by patient_id order by load_date) grp
   from (
      select *,
         lag(monthstart, 1, DATE_ADD(monthstart, interval -1 month)) over(partition by patient_id order by load_date) <> DATE_ADD(monthstart, interval -1 month) seq
      from (
            select *, DATE_ADD(load_date, interval - day(load_date)+1 day) monthstart
            from events
           )t
       ) t
    )t
group by patient_id, grp
order by patient_id, min(load_date)

将其翻译回 5.7:

select patient_id,  min(load_date) s,  max(load_date) e
from (
     select *, 
        (select sum(seq)
         from(
             select *, 
                not exists(
                   select 1 
                   from events e2
                   where DATE_ADD(t.monthstart, interval -1 month) = DATE_ADD(e2.load_date, interval - day(e2.load_date)+1 day) and t.patient_id = e2.patient_id
                          ) seq
             from (
                  select *, DATE_ADD(load_date, interval - day(load_date)+1 day) monthstart
                  from events
                  ) t
              ) t 
         where t.patient_id = e.patient_id and t.load_date <= e.load_date) grp
     from events e
     ) t
group by patient_id, grp
order by patient_id, min(load_date)

db<>fiddle