重叠日期跨度

时间:2018-02-08 02:40:25

标签: sql sql-server

我有下表。我怎么才能找到重叠的跨度?例如,下面的memberid 3不应该在我们的范围内,因为日期跨度不会相互重叠

非常感谢任何帮助

MemberID    fromdate    todate
1   1/1/2018    12/31/2018
1   1/1/2018    12/31/2018
2   12/1/2017   1/1/2019
2   1/2/2018    2/2/2019
3   1/1/2015    12/31/2015
3   1/1/2016    12/31/2016
3   1/1/2017    12/31/2017
4   1/1/2018    1/1/2018
4   1/1/2018    1/1/2018
5   1/1/2015    1/31/2016
5   1/1/2016    7/31/2016
5   07/01/2016  12/31/2016

预期结果应该是与会员ID 1,2,4和5相关的数据会员ID 3不应该在结果集中,因为日期跨度不重叠。

2 个答案:

答案 0 :(得分:0)

嗯。您可以通过执行以下操作来获取重叠跨度:

select m.*
from members m
where exists (select 1
              from members m2
              where m2.memberid = m.memberid and
                    m2.todate > m.fromdate and m2.fromdate < m.todate
             );

如果您希望成员不重叠,请使用except

select m.memberid
from members m
except
select m.*
from members m
where exists (select 1
              from members m2
              where m2.memberid = m.memberid and
                    m2.todate >= m.fromdate and m2.fromdate <= m.todate
             );

Except删除重复项。但是如果你想要更加确定和冗余,你可以为每个查询写select distinct

答案 1 :(得分:0)

试试这个:

;with cte as
(select memberid, convert(Varchar,fromdate,101)fromdate,convert(Varchar,todate,101)todate from @tb),
cte2 as 
(select Num,memberid,todate,fromdate,Num + 1 as num2 from 
(select  ROW_NUMBER() over(partition by memberid order by fromdate) as Num,memberid,fromdate,todate from cte) as a),
cte3 as
(select memberid,fromdate,todate, DATEDIFF(day,fromdate,todate) as date_diff from
(select ISNULL(memberid,bnum)memberid , isnull(fromdate1,fromdate2)fromdate,isnull(fromdate2,fromdate1)todate,bnum from
(select a.num,a.fromdate,a.todate,a.num2 as num1,a.memberid,case when a.Num=b.num2 then b.todate else a.fromdate end as fromdate1,
case when a.Num=b.num2 then a.fromdate else  b.todate end as fromdate2,b.num2,b.todate as todate2,b.Num as bnum from cte2 as a
full join cte2 as b
on a.num = b.num2 and a.memberid = b.memberid) as a) as a)

select distinct memberid  from cte3 where date_diff<0