我有一个包含3列的表:clientid、start_date、end_date
每一行都是一次护理,客户可以有多次护理。我正试图在SQL Server中编写一个查询,该查询将显示最近一期护理的开始和结束日期,前提是该日期比前一期护理结束日期晚21天。有人能帮忙吗?
"我不知道如何将一集(第1行(的结束日期与下一集的开始日期(第2行(进行比较。"很简单,但不能在where子句或计算的差异中使用窗口函数,这意味着使用子查询(或cte(来完成的大部分工作
drop table t
go
create table t
(clientid int, start_date date, end_date date);
go
insert into t values
(1,'2022-09-01','2022-09-01'),
(1,'2022-09-10','2022-09-10')
go
select * from
(
select *,
lag(end_date) over (partition by clientid order by start_date) lage,
datediff(d,lag(end_date) over (partition by clientid order by start_date),start_date) diff
from t
) s
where diff = 9
clientid start_date end_date lage diff
----------- ---------- ---------- ---------- -----------
1 2022-09-10 2022-09-10 2022-09-01 9
(1 row(s) affected)
LAG为我工作。感谢您的帮助。