0

I have a table contains ids and dates, I want to groups of dates for each id

 id      date 
 ------------------
  1      2019-01-01
  2      2019-01-01
  1      2019-01-02
  2      2019-01-02
  2      2019-01-03
  1      2019-01-04
  1      2019-01-05
  2      2019-01-05
  2      2019-01-06

I want to check where are gaps in date for each id to get output like

id      from             to
------------------------------------
 1      2019-01-01       2019-01-02
 1      2019-01-04       2019-01-05
 2      2019-01-01       2019-01-03
 2      2019-01-05       2019-01-06
0

2 Answers 2

3

This is a form of gaps-and-islands problem. The simplest solution is to generate a sequential number for each id and subtract that from the date. This is constant for dates that are sequential.

So:

select id, min(date), max(date)
from (select t.*, row_number() over (partition by id order by date) as seqnum
      from t
     ) t
group by id, dateadd(day, -seqnum, date)
order by id, min(date);

Here is a db<>fiddle.

Sign up to request clarification or add additional context in comments.

Comments

0

A typical approach to this gaps-and-islands problem is build the groups by comparing the date of the current record to the "previous" date of the same id. When dates are not consecutive, a new group starts:

select id, min(date) from_date, max(date) to_date
from (
    select 
        t.*, 
        sum(case when date = dateadd(day, 1, lag_date) then 0 else 1 end) 
            over(partition by id order by date) grp
    from (
        select 
            t.*, 
            lag(date) over(partition by id order by date) lag_date
        from mytable t
    ) t
) t
group by id, grp
order by id, from_date

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.