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

4sup72z8  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(310)

空载日期1232021-03-0111232021-02-0111232021-01-0111232020-12-3111232020-11-131232020-05-141232020-04-161232019-01-16
这些是我对某个特定成员的日期列表,我想将其转换为连续日期的日期范围(基于月份和年份)
预期结果:
成员起始日期成员终止日期2019-01-162019-01-162020-04-162020-05-142020-11-132021-03-01
我想使用mysql5.7的sql qry的结果任何帮助都将不胜感激。

9nvpjoqh

9nvpjoqh1#

这在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<>小提琴

相关问题