首页 > 解决方案 > 查找重叠日期并在 SQL Server 中排除它们?

问题描述

这是我的表“地图”的一部分:例如,比较 A 和 D 行。A 日期范围完全在 D 日期范围内,因此我们要删除该行。(我不想删除这一行,但我的查询结果不应该显示该行)。

sed id      code    startdate   enddate
101 1019    A       2002-12-02  2009-11-17 
101 1019    B       1986-01-02  2009-11-04 
101 1019    C       2009-07-01  2009-11-17 
101 1019    C       2002-12-02  2009-06-30 
101 1019    D       1986-01-03  2009-11-17 
101 1019    E       2007-10-15  2009-11-17 
101 1019    E       1992-01-31  1999-08-30 
101 1019    F       2007-11-26  2009-11-05 
101 1019    F       2007-09-05  2007-11-22 
101 1019    F       2007-07-06  2007-09-03 

标签: sqlsql-server

解决方案


这似乎可以回答您的问题:

select t.*
from t
where not exists (select 1
                  from t t2
                  where t2.startdate < t.startdate and t2.enddate >= t.enddate and
                        t2.sed = t.sed and t2.id = t.id and t2.code <> t.code
                 );

推荐阅读