我有一个表格,其中包含患者的医院就诊情况。我正在尝试标记上次访问后90天内发生的访问。但是,需要注意的是,一旦将某个访问标记为重复访问,就不应将该访问用于评估与另一个访问的重复。让我用一个例子来解释。
visitID patientid visit_date
1 23 1/12/2018
2 23 1/30/2018
3 23 4/20/2018
4 23 5/02/2018
在上面的示例中,患者进行了4次就诊。访问2在访问1的90天内,因此应将访问2标记为重叠。标记访问2后,该行就不应在分析中用于以后的任何访问的重叠标识。从概念上讲,这就像删除访问2并再次开始分析。
过渡阶段(访问2被删除,分析再次开始)
visitID patientid visit_date
1 23 1/12/2018
3 23 4/20/2018
4 23 5/02/2018
因此,即使访问3与访问2重叠,由于已将访问2从分析中删除,因此访问3不会被标记为上一次访问(访问1)的时间超过90天。最后,应标记4次访问,因为它与未标记的访问重叠。
visitID patientid visit_date flag
1 23 1/12/2018 0
2 23 1/30/2018 1
3 23 4/20/2018 0
4 23 5/02/2018 1
我解决这个难题的尝试:
WITH overlaps AS
(SELECT DISTINCT T2.visit
FROM visits_table AS T1
INNER JOIN visits_table AS T2
ON T1.visit != T2.visit
AND T2.visit_date BETWEEN T1.visit_date AND DATEADD(DAY, 89, T1.visit_date))
SELECT T3.visit, T3.patientid, T3.visit_date,
CASE WHEN EXISTS (SELECT 1 FROM overlaps
WHERE overlaps.visit = T3.visit)
THEN 1
ELSE 0
END flag
FROM visits_table T3
我的代码正在执行的操作是检查每一行,而不管是否应在分析中使用它。我不知道如何使其动态,以便它忽略应忽略的行。
create table visits_table (visit int,patientid int,visit_date date);
INSERT INTO visits_table (visit, patientid, visit_date) VALUES (1,23,'1/12/2018')
INSERT INTO visits_table (visit, patientid, visit_date) VALUES (2,23,'1/30/2018')
INSERT INTO visits_table (visit, patientid, visit_date) VALUES (3,23,'4/20/2018')
INSERT INTO visits_table (visit, patientid, visit_date) VALUES (4,23,'5/02/2018')
答案 0 :(得分:6)
我相信您必须使用递归CTE来做到这一点:
with vt as (
select vt.*, row_number() over (partition by patientid order by visit_date) as seqnum
from visits_table vt
),
cte as (
select vt.visit, vt.patientid, vt.visit_date, vt.visit_date as first_visit_date, seqnum
from vt
where seqnum = 1
union all
select vt.visit, vt.patientid, vt.visit_date,
(case when vt.visit_date > dateadd(day, 90, cte.first_visit_date) then vt.visit_date else cte.first_visit_date end),
vt.seqnum
from cte join
vt
on vt.seqnum = cte.seqnum + 1 and vt.patientid = cte.patientid
)
select cte.visit, cte.patientid, cte.visit_date,
(case when first_visit_date = visit_date then 0 else 1 end) as flag
from cte
order by cte.patientid, cte.visit_date;
Here是db <>小提琴。