如何根据日期删除重叠的行并在sql中保持最新?

时间:2018-07-01 23:57:52

标签: sql sql-server overlapping

我需要为每个患者找到所有的Episode_id。但是,如果前一个90天内出现重叠的情节,那么我只想保留最近的情节。

例如,下面的patient_num 3242有3集:第二集与90天内的第一集重叠,第三集与90天内的第二集重叠,在这种情况下,我需要保持第三集。

CREATE TABLE table1 (episode_id nvarchar(max), patient_num nvarchar(max), admit_date date,  discharge_date date)

INSERT INTO table1 (episode_id, patient_num , admit_date ,  discharge_date ) VALUES 
('1','5743','1/1/2016','1/5/2016'),
('2','5743','4/26/2016','4/29/2016'),
('3','5743','5/26/2016','5/28/2016'),
('4','5743','9/21/2016','9/28/2016'),
('5','8859','4/27/2016','5/5/2016'),
('6','3242','4/28/2016','4/29/2016'),
('7','3242','11/21/2016','11/23/2016'),
('8','3242','11/24/2016','11/29/2016'),
('9','3242','12/12/2016','12/29/2016')

初始表(表1)

episode_id   patient_num  admit_date   discharge_date
1            5743         2016-01-01   2016-01-05 
2            5743         2016-04-26   2016-04-29
3            5743         2016-05-26   2016-05-28
4            5743         2016-09-21   2016-09-28
5            8859         2016-04-27   2016-05-05
6            3242         2016-04-28   2016-04-29
7            3242         2016-11-21   2016-11-23
8            3242         2016-11-24   2016-11-29
9            3242         2016-12-12   2016-12-29

预期结果

episode_id   patient_num  admit_date   discharge_date
1            5743         2016-01-01   2016-01-05 
3            5743         2016-05-26   2016-05-28
4            5743         2016-09-21   2016-09-28
5            8859         2016-04-27   2016-05-05
6            3242         2016-04-28   2016-04-29
9            3242         2016-12-12   2016-12-29

我的尝试

SELECT *
FROM table1 AS a
WHERE EXISTS
(
    SELECT *
    FROM table1 AS b
    WHERE      a.episode_id != b.episode_id
               AND a.patient_num= b.patient_num
               AND a.admit_date BETWEEN b.discharge_date AND DATEADD(DAY, 90, b.discharge_date ))

我的脚本中的错误是,对于患者编号3242,我得到的插曲ID 8和9都只需要第9集。我假设发生此错误的原因是我在比较每行而不是单独分组,但分组时遇到麻烦。另外,此脚本未显示没有重叠的实例,例如Episode_id 1、4、5、6。有关此方法的任何建议吗?

2 个答案:

答案 0 :(得分:2)

我在这里删除了游标解决方案,因为它的性能较低 不使用游标的解决方案是:

WITH ExcludedIds AS (
SELECT DISTINCT T2.episode_id 
FROM table1  AS T 
INNER JOIN table1 AS T2 ON T.episode_id != T2.episode_id
               AND T.patient_num = T2.patient_num
               AND T2.discharge_date BETWEEN DATEADD(DAY, -90, T.admit_date ) AND  T.discharge_date)

SELECT T.episode_id, T.patient_num, T.admit_date, T.discharge_date 
FROM table1 AS T 
WHERE T.episode_id NOT IN (SELECT ExcludedIds.episode_id FROM ExcludedIds)

想了解这种解决方案有点困难。

答案 1 :(得分:-1)

我认为not exists是您想要的:

SELECT a.*
FROM table1 a
WHERE NOT EXISTS (SELECT 1
                  FROM table1 b
                  WHERE a.episode_id <> b.episode_id AND
                        a.patient_num = b.patient_num AND
                        b.admin_date < a.discharge_date AND
                        b.discharge_date >= DATEADD(DAY, -90, a.discharge_date)
                 );