SQL查找两个日期范围之间的重复活动记录

时间:2019-06-27 09:36:53

标签: sql date sql-server-2008

我有两个表,一个病人表和一个保险表。一位患者可以拥有多种保险。我正在尝试查找所有有效日期重叠或显示两个处于有效状态的保险。

PATID    START_DTTM           END_DTTM
1        2002-09-10 00:00:00.000  NULL
1        2007-03-06 10:18:00.000  2019-04-11 11:59:00.000

如果END_DTTM为Null,则它处于活动状态。开始日期应在后续结束日期结束时开始。我试图找到所有有效日期重叠的条目,或者在一段时间内显示两个有效条目的条目?

另外,患者可以拥有多种保险,以上示例显示了具有两种保险详细信息的患者。他们也可能有第三或第四项...

任何帮助都会很棒

2 个答案:

答案 0 :(得分:1)

这将列出所有至少有一个其他保险重叠的保险。

select ID, PATID, START_DTTM, END_DTTM
from insurances i1
where exists (select null 
              from insurances i2
              where i1.ID != i2.ID and i1.PATID = i2.PATID
                and (i1.START_DTTM  <= i2.END_DTTM or i2.END_DTTM is null)
                and (i2.START_DTTM  <= i1.END_DTTM or i1.END_DTTM is null)
             )
order by PATID, START_DTTM;

两个有效的保险(截止日期为零)被认为是重叠的。如果不认为相等的开始日期/结束日期重叠,您可能希望将<=更改为<

答案 1 :(得分:0)

如果您的保险表中每个保险都有唯一的ID(我们希望如此),那么您可以进行这样的查询

declare @tab table (
    patid int
    , insid int
    , start_dttm datetime
    , end_dttm datetime
)

insert into @tab values (1, 8, '2002-09-10', NULL)
                        , (1, 9, '2007-03-06', '2019-04-11')
                        , (53, 321513, '2015-01-13', NULL )
                        , (53, 11, '2008-08-14', '2015-01-13')
                        , (54, 12, '2015-01-13', NULL )
                        , (54, 13, '2008-08-14', '2015-01-12')

select      a.*
            , b.*
            , 'Insurance record ' + cast(b.insid as varchar) + ' (' + convert(varchar,b.start_dttm,103) + ' to ' + convert(varchar,b.end_dttm,103) + ') '
             + 'overlaps Insurance record ' + cast(a.insid as varchar) + ' (' + convert(varchar,a.start_dttm,103) + isnull(' to ' + convert(varchar,a.end_dttm,103), ' still active') + ')'

from        @tab a
inner join  @tab b
on          a.patid = b.patid
and         a.insid != b.insid
where       (b.start_dttm > a.start_dttm and b.start_dttm < isnull(a.end_dttm, getdate()+1))
or          (b.end_dttm > a.start_dttm and b.start_dttm < isnull(a.end_dttm, getdate()+1))
or          (a.end_dttm is null and b.end_dttm is null)

注意-您不需要像我一样创建表变量@tab,只需使用您的保险表即可。