2011-02-18 51 views
3

我已經發現了很多關於如何找到重複的,包括PK列或不專注於它,因爲這答案:查找幾列重複專屬ID列

如果你有一個名爲T1的表,並且列是c1,c2和c3,則此查詢將顯示重複值。

SELECT C1, C2, C3, count(*)as DupCount 
from T1 
GROUP BY C1, C2, C3 
HAVING COUNT(*) > 1 

但更常見的要求是獲得具有相同c1,c2,c3值的所有重複項的ID。

,所以我需要以下什麼行不通,因爲ID,必須綜合:

SELECT ID 
from T1 
GROUP BY C1, C2, C3 
HAVING COUNT(*) <> 1 

(將所有重複的ID必須是不同的,但列必須等於)

編輯

謝謝大家。我總是驚訝人們在Stackoverflow上給出了很好的答案!

+0

你能提供一些樣本數據嗎? – 2011-02-18 15:31:48

回答

5

這裏有很多版本,但我想我想出了一個新的。

select * 
from @T as T1 
where exists (select * 
       from @T as T2 
       where 
       T1.ID <> T2.ID and 
       T1.C1 = T2.C1 and 
       T1.C2 = T2.C2 and 
       T1.C3 = T2.C3) 
3
;WITH CTE 
    AS (SELECT ID, 
       C1, 
       C2, 
       C3, 
       COUNT(*) OVER (PARTITION BY C1, C2, C3) AS Cnt 
     FROM T1) 
SELECT ID, 
     C1, 
     C2, 
     C3 
FROM CTE 
WHERE Cnt > 1 
+0

這個答案假定sql server> = 2005? – 2011-02-18 15:35:20

+0

@Nathan - 是的。現在是2011年,如果OP需要2000年兼容的解決方案,他們應該在問題中說明它! – 2011-02-18 15:39:03

+0

@Martin當然,但我錯過了sqlserver的問題,或者可以假設,因爲這是SO。 :) – 2011-02-18 15:42:00

0

我不完全理解你的問題,但在這裏是一個不同風格的解決方案一拍:

select id 
from t1 a 
join t1 b on a.c1 = b.c2 
join t1 c on b.c2 = c.c3 
where a.id <> b.id and b.id <> c.id and a.id <> c.id 
3

要得到所有的是重複的行:

使用此:

WITH Dups AS 
(
    SELECT *, 
      COUNT(1) OVER(PARTITION BY C1, C2, C3) AS CNT 
     FROM T1 
) 
SELECT * 
    FROM Dups 
WHERE CNT > 1 

和唯一行(即保留一行並過濾其他重複行)使用此:

WITH NoDups AS 
(
    SELECT *, 
     ROW_NUMBER() OVER(PARTITION BY C1, C2, C3 ORDER BY ID) AS RN 
     FROM T1 
) 
SELECT * 
    FROM NoDups 
WHERE RN = 1 
1

假設至少是SQL 2005的CTE:

;with cteDuplicates as (
    select c1, c2, c3 
     from t1 
     group by c1, c2, c3 
     having count(*) > 1 
) 
select id 
    from t1 
     inner join cteDuplicates d 
      on t1.c1 = d.c1 
       and t1.c2 = d.c2 
       and t1.c3 = d.c3 
0

您可以重複的C1,C2,C3組合存儲到一個臨時表中,然後加入它得到的ID。

select C1, C2, C3 
into #duplicates 
from T1 
group by C1, C2, C3 
having count(*) > 1 

select ID 
from T1 t 
inner join #duplicates d 
    on t.C1 = d.C1 
    and t.C2 = d.C2 
    and t.C3 = d.C3