简体   繁体   中英

SQL - convert date column to start and end dates

I'm trying to take a column of dates and create a new table that includes the start and end date of each continuous date range. For example (date format being mm/dd/yyyy):

id date
2 01/02/2022
5 01/03/2022
5 01/04/2022
5 01/05/2022
6 01/02/2022
6 01/04/2022
6 01/05/2022

would create the following table:

id start end
2 01/02/2022 01/02/2022
5 01/03/2022 01/01/2022
6 01/02/2022 01/02/2022
6 01/04/2022 01/05/2022

Use below

select id, min(cur_date) start, max(cur_date) as `end`
from (
  select *, countif(date_diff(next_date, cur_date, day) != 1) over win as grp
  from (
  select id, date, cur_date,
    ifnull(lead(cur_date) over(partition by id order by cur_date), cur_date) next_date
  from your_table, unnest([struct(parse_date('%m/%d/%Y', date) as cur_date)])
  )
  window win as (partition by id order by cur_date rows between unbounded preceding and 1 preceding)
)
group by id, grp               

if applied to sample data in your question - output is

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM