在大家的尊敬和恕我直言,
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
操作,这比将诸如>,<之类的运算符放入APPDate中更为有效。inequality
在APPID中放置 >,<之类的运算符将有助于Sql Optimizer。
还应该在表中有两个日期列
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)
使用其他样本数据和lemme测试我的脚本,以了解它不适用于哪些样本数据。即使它不起作用,也可以在脚本逻辑本身中解决。
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