在SP-SQL Server中查找重复记录而不循环

时间:2015-02-17 10:03:48

标签: sql sql-server tsql

我有这个结构和样本数据的表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 

此处'参考'不和' CID'每条记录的价值变化(我已将其记录为单一记录),我必须只考虑最新的R日期

当我使用不同的验证处理循环中的10000条记录时,上面的查询会占用大量时间。如何提高上述查询性能。

4 个答案:

答案 0 :(得分:1)

;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

答案 1 :(得分:0)

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

答案 2 :(得分:0)

请确保在Reference和CID上创建了复合群集/非群集索引。否则,所有查询都会非常慢。

答案 3 :(得分:0)

使用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)