Search code examples
sqlsql-serversql-server-2017

Find non consecutive date ranges


i want to find if some of all the consecutive date ranges has gap between. Some of the dates are not consecutive, in this case it will return the RowId of the single range.

Table Name: Subscriptions

RowId ClientId Status StartDate EndDate
1 1 1 01/01/2022 02/01/2022
2 1 1 03/01/2022 04/01/2022
3 1 1 12/01/2022 15/01/2022
4 2 1 03/01/2022 06/01/2022

i want a sql statement to find RowId of non consecutive ranges for each client and status in (1,3) (example of result)

RowId
3

I want to solve the problem using SQL only. thanks


Solution

  • You can detect gaps with LAG() and mark them. Then, it's easy to filter out the rows. For example:

    select *
    from (
      select *,
        case when dateadd(day, -1, start_date) >
           lag(end_date) over(partition by client_id order by start_date) 
        then 1 else 0 end as i
      from t
    ) x
    where i = 1
    

    Or simpler...

    select *
    from (
      select *,
        lag(end_date) over(partition by client_id order by start_date) as prev_end
      from t
    ) x
    where dateadd(day, -1, start_date) > prev_end