在 SP 中查找重复记录而不循环 - SQL 服务器

Finding duplicate record without looping in SP - SQL Server

我 table T1 具有以下结构和示例数据:

ID  CID Reference   Rdate 
--------------------------------
1   123 REF65798    11/11/2011
2   123 REF65798    11/11/2011
3   156 REF65798    11/3/2011
4   156 REF65798    11/11/2011
5   181 REF65798    11/5/2011
6   181 REF65798    11/10/2011

现在在我的程序中针对不同的参考编号是否有任何重复记录存在相同 Rdate:

declare @Duplicate int

select top 1 
     @Duplicate = count(*) 
from 
    (select Rdate 
     from t1 
     where Reference = 'REF65798' 
       and CID in (123, 156, 181)
     order by Rdate desc) A
group by 
    a.Rdate 

这里 'Reference' 没有和 'CID' 每条记录的值变化(我已经为单个记录给出了它)并且我只需要考虑最新的 R 日期

当我使用不同的验证循环处理 10000 条记录时,上述查询会花费很多时间。如何提高上述查询性能。

SELECT Rdate
FROM   t1
WHERE  Reference = 'REF65798'
       AND CID IN (123, 156, 181)
GROUP BY
       Rdate
HAVING COUNT(*) >= 2

请确保您已在 Reference 和 CID 上创建了复合 clustered/non-clustered 索引。否则所有查询都会很慢。

;WITH CTE as
(
  SELECT 
    ID, CID, Reference, Rdate, 
    row_number() over(partition by CID order by Rdate DESC) rn
  FROM yourtable
  WHERE 
    Reference = 'REF65798' and
    CID in (123, 156, 181)
)
SELECT 
  ID, CID, Reference, Rdate
FROM CTE
WHERE 
  rn = 1

使用 EXISTS 查找包含同一日期且 ID 更早的条目的行:

select *
from t1 as t1main
where Reference = 'REF65798' 
  and CID in (123, 156, 181)
  and exists (select 1 from t1
              where Reference = 'REF65798' 
                and CID in (123, 156, 181)
                and Rdate = t1main.Rdate
                and id < t1main.id)