我想找出所有連續日期范圍中的一些是否有差距。有些日期不是連續的,在這種情況下它將回傳單個范圍的 RowId。
表名:訂閱
| 行 ID | 客戶 ID | 地位 | 開始日期 | 結束日期 |
|---|---|---|---|---|
| 1 | 1 | 1 | 2022 年 1 月 1 日 | 2022 年 2 月 1 日 |
| 2 | 1 | 1 | 2022 年 3 月 1 日 | 2022 年 4 月 1 日 |
| 3 | 1 | 1 | 2022 年 12 月 1 日 | 15/01/2022 |
| 4 | 2 | 1 | 2022 年 3 月 1 日 | 2022 年 6 月 1 日 |
我想要一個 sql 陳述句來查找每個客戶端的非連續范圍的 RowId 和 (1,3) 中的狀態(結果示例)
| 行 ID |
|---|
| 3 |
我只想使用 SQL 來解決問題。謝謝
uj5u.com熱心網友回復:
您可以執行此操作的一種方法是使用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;
uj5u.com熱心網友回復:
您可以檢測間隙LAG()并標記它們。然后,很容易過濾掉行。例如:
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
或者更簡單...
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
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/486994.html
