Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/sql-server-2008/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql server 2008 TSQL根据日期范围确定重复项_Sql Server 2008_Tsql - Fatal编程技术网

Sql server 2008 TSQL根据日期范围确定重复项

Sql server 2008 TSQL根据日期范围确定重复项,sql-server-2008,tsql,Sql Server 2008,Tsql,我正在努力使用适当的查询来查找重复项,同时还要考虑记录的有效开始和结束日期。下面是示例数据 ClientName ClientID EffectiveStart EffectiveEnd A 1 1900-01-01 2100-01-01 A 1 1900-01-01 2100-01-01 B 2 1900-01-01 2012-05-0

我正在努力使用适当的查询来查找重复项,同时还要考虑记录的有效开始和结束日期。下面是示例数据

ClientName ClientID EffectiveStart EffectiveEnd A 1 1900-01-01 2100-01-01 A 1 1900-01-01 2100-01-01 B 2 1900-01-01 2012-05-01 C 2 2012-05-01 2100-01-01 D 3 1900-01-01 2012-05-01 E 3 2012-04-30 2100-01-01 F 4 2012-04-15 2100-01-01 我正在寻找的输出如下

ClientName ClientID A 1 D 3 E 3 逻辑是客户端A的ID 1重复。客户B和客户C有一个重复的2,但日期范围是这样的,即两个重复不相互重叠,这意味着它们不应被视为重复。客户D和E的ID 3重复,并且日期范围重叠,因此应将其视为重复。客户端F没有副本,因此不应显示在输出中

有什么想法吗?问题?

需要PK

select c1.name, c2.name, c1.id
from client c1 
join client c2 on c1.id = c2.id and c1.PK < c2.PK
where c1.Start > c2.End or c1.End < c2.Start

请给他一个+1,有两个版本。Exists较简单,但可能比join慢。Exists检查每个记录是否存在每个相同clientid的重叠记录;它一定会找到至少一个,即它自己,因此它是分组的,并且具有

select distinct ClientName, ClientID
  from Table1
 where exists
 (
   select null
     from table1 test1
    where test1.clientid = table1.clientid
      and test1.EffectiveStart < table1.EffectiveEnd
      and test1.EffectiveEnd > table1.EffectiveStart
    group by test1.ClientID
   having count (*) > 1
 )
Join的作用是相同的,但当对所有记录进行分组时,它必须对所有记录进行计数

select test1.clientid
from table1 test1 
join table1 test2 on test1.clientid = test2.clientid
where test1.EffectiveStart < test2.EffectiveEnd 
  and test1.EffectiveEnd > test2.EffectiveStart
group by test1.clientid
having count (*) > (select count (*) 
                      from table1 
                     where clientid = test1.clientid)
我省略了对clientname的检索,因为人们不喜欢看到嵌套查询


现场测试正在进行。

这已成功。谢谢我已经知道了检查相交日期范围的逻辑…只是不知道如何将它们连接在一起。PK是我的关键。谢谢这也很棒。从来没见过SQL乱来。很好。我将在将来使用它。