尊重每一个人,恕我直言,
There is not much difference between While LOOP and Recursive CTE in terms of RBAR
同时使用Recursive CTE 和Window Partition function 并没有太大的性能提升。
Appid 应该是 int identity(1,1) ,或者应该不断增加 clustered index。
除了其他好处之外,它还确保该患者的所有连续行APPDate 必须更大。
通过这种方式,您可以轻松地在查询中使用APPID,这比将inequality 运算符(如>、inequality 运算符如 >,
表中也应该有两个日期列
APPDateTime datetime2(0) not null,
Appdate date not null
因为这些是最重要的表中最重要的列,所以没有太多的转换,转换。
所以Non clustered index可以在Appdate上创建
Create NonClustered index ix_PID_AppDate_App on APP (patientid,APPDate) include(other column which is not i predicate except APPID)
用其他示例数据测试我的脚本,然后让我知道它不适用于哪些示例数据。
即使它不起作用,我相信它可以在我的脚本逻辑本身中修复。
CREATE TABLE #Appt1 (ApptID INT, PatientID INT, ApptDate DATE)
INSERT INTO #Appt1
SELECT 1,101,'2020-01-05' UNION ALL
SELECT 2,505,'2020-01-06' UNION ALL
SELECT 3,505,'2020-01-10' UNION ALL
SELECT 4,505,'2020-01-20' UNION ALL
SELECT 5,101,'2020-01-25' UNION ALL
SELECT 6,101,'2020-02-12' UNION ALL
SELECT 7,101,'2020-02-20' UNION ALL
SELECT 8,101,'2020-03-30' UNION ALL
SELECT 9,303,'2020-01-28' UNION ALL
SELECT 10,303,'2020-02-02'
;With CTE as
(
select a1.* ,a2.ApptDate as NewApptDate
from #Appt1 a1
outer apply(select top 1 a2.ApptID ,a2.ApptDate
from #Appt1 A2
where a1.PatientID=a2.PatientID and a1.ApptID>a2.ApptID
and DATEDIFF(day,a2.ApptDate, a1.ApptDate)>30
order by a2.ApptID desc )A2
)
,CTE1 as
(
select a1.*, a2.ApptDate as FollowApptDate
from CTE A1
outer apply(select top 1 a2.ApptID ,a2.ApptDate
from #Appt1 A2
where a1.PatientID=a2.PatientID and a1.ApptID>a2.ApptID
and DATEDIFF(day,a2.ApptDate, a1.ApptDate)<=30
order by a2.ApptID desc )A2
)
select *
,case when FollowApptDate is null then 'New'
when NewApptDate is not null and FollowApptDate is not null
and DATEDIFF(day,NewApptDate, FollowApptDate)<=30 then 'New'
else 'Followup' end
as Category
from cte1 a1
order by a1.PatientID
drop table #Appt1