简体   繁体   English

查找非连续日期范围

[英]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.有些日期不是连续的,在这种情况下它将返回单个范围的 RowId。

Table Name: Subscriptions表名:订阅

RowId行 ID ClientId客户 ID Status地位 StartDate开始日期 EndDate结束日期
1 1 1 1 1 1 01/01/2022 2022 年 1 月 1 日 02/01/2022 2022 年 2 月 1 日
2 2 1 1 1 1 03/01/2022 2022 年 3 月 1 日 04/01/2022 2022 年 4 月 1 日
3 3 1 1 1 1 12/01/2022 2022 年 12 月 1 日 15/01/2022 15/01/2022
4 4 2 2 1 1 03/01/2022 2022 年 3 月 1 日 06/01/2022 2022 年 6 月 1 日

i want a sql statement to find RowId of non consecutive ranges for each client and status in (1,3) (example of result)我想要一个 sql 语句来查找每个客户端的非连续范围的 RowId 和 (1,3) 中的状态(结果示例)

RowId行 ID
3 3

I want to solve the problem using SQL only.我只想使用 SQL 来解决问题。 thanks谢谢

One way you could do this is to use Lag (or lead ) to identify gaps in neighbouring rows' date ranges and take the top N rows where the gap exceeds 1 day.您可以执行此操作的一种方法是使用Lag (或Lead )来识别相邻行日期范围中的差距,并获取差距超过 1 天的前 N ​​行。

select top (1) with ties rowId 
from t
where status in (1,3)
order by 
  case when DateDiff(day, lag(enddate,1,enddate) 
    over(partition by clientid order by startdate), startdate) >1 
  then 0 else 1 end;

You can detect gaps with LAG() and mark them.您可以使用LAG()检测间隙并标记它们。 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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