【发布时间】:2019-09-30 21:28:01
【问题描述】:
我有一张表格,其中包含患者就诊的情况。我正在尝试标记访问“begin_date”与之前的访问“end_date”重叠 90 天的访问。但是,需要注意的是,一旦一次访问被标记为重叠访问,则不应使用该访问来评估与另一次访问的重叠。让我用一个例子来解释。
表格
visitID patientid begin_date end_date
1 23 1/12/2018 1/14/2018
2 23 1/30/2018 2/14/2018
3 23 4/20/2018 4/22/2018
4 23 5/02/2018 5/03/2018
5 23 7/23/2018 7/28/2018
在上面的示例中,患者进行了 5 次就诊。访问 2 的 begin_date 在访问 1 的 end_date + 90 天的范围内,因此应标记访问 2。标记访问 2 后,该行不应在分析中用于任何未来访问。从概念上讲,这就像删除访问 2 并重新开始分析。
中间阶段(访问 2 被移除,分析重新开始)
visitID patientid begin_date end_date
1 23 1/12/2018 1/14/2018
3 23 4/20/2018 4/22/2018
4 23 5/02/2018 5/03/2018
5 23 7/23/2018 7/28/2018
所以即使访问 3 与访问 2 重叠,由于访问 2 已被删除,访问 3 不会被标记为上一次访问(现在访问 1)超过 end_date + 90 天后访问 3 的 @987654331 @。然后,应该标记访问 4,因为它与未标记的访问(访问 3)重叠。因此,由于标记了访问 4,因此将删除访问 5,因为它的 begin_date 在访问 3 的 end_date + 90 天的范围内。
预期输出
visitID patientid begin_date end_date flag
1 23 1/12/2018 1/14/2018 0
2 23 1/30/2018 2/14/2018 1
3 23 4/20/2018 4/22/2018 0
4 23 5/02/2018 5/03/2018 1
5 23 7/23/2018 7/28/2018 1
@gordonlinoff 回答了一个非常相似的问题here,但我在使用递归 CTE 时遇到了问题。问题之间的区别在于,这个问题需要引用另一列 (end_date),而不是单个日期列。递归 CTE 对我来说仍然是一个新概念,但我希望这将有助于巩固这个概念。
我尝试解决这个难题(从@gordonlinoff 中退出):
with vt as (
select vt.*, row_number() over (partition by patientid order by begin_date) as seqnum
from visits_table vt
),
cte as (
select vt.visit, vt.patientid, vt.begin_date, vt.end_date, vt.begin_date as first_begin_date, seqnum
from vt
where seqnum = 1
union all
select vt.visit, vt.patientid, vt.begin_date, vt.end_date,
(case when vt.begin_date > dateadd(day, 90, cte.end_date) then vt.begin_date else cte.end_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.begin_date, cte.end_date,
(case when first_begin_date = begin_date then 0 else 1 end) as flag
from cte
order by cte.patientid, cte.begin_date;
我的编辑根据结果不正确地引用了 end_date。但是,我找不到begin_date 和end_date 之间的比较应该在哪里。
数据集:
create table visits_table (visit int,patientid int,begin_date date, end_date date);
INSERT INTO visits_table (visit, patientid, begin_date, end_date) VALUES (1,23,'1/12/2018','1/14/2018')
INSERT INTO visits_table (visit, patientid, begin_date, end_date) VALUES (2,23,'1/30/2018','2/14/2018')
INSERT INTO visits_table (visit, patientid, begin_date, end_date) VALUES (3,23,'4/20/2018','4/22/2018')
INSERT INTO visits_table (visit, patientid, begin_date, end_date) VALUES (4,23,'5/02/2018','5/03/2018')
【问题讨论】:
标签: sql sql-server recursion common-table-expression