2012-04-25 63 views
2

它是一個Sql查詢。sql雙多列鍵

我想知道重複的數據。

樣品:

Table 1 
Col1, col2, col3, col4 
1, A, AA, AAA 
2, A, BB, AAA 
3, A, BB, AAA 
4, B, AA, AAA 
5, B, AA, BBB 
6, B, AA, CCC 
7, B, BB, AAA 
8, B, CC, AAA 

的結果應該是:

2, A, BB, AAA 
3, A, BB, AAA 

或者

A, BB, AAA 

這樣我就可以發現哪裏還有我的雙打。

謝謝。

回答

2

你也可以做這樣的:

測試數據

DECLARE @T TABLE(Col1 int, col2 VARCHAR(100), col3 VARCHAR(100), 
       col4 VARCHAR(100)) 

INSERT INTO @T 
VALUES 
    (1, 'A', 'AA', 'AAA'), 
    (2, 'A', 'BB', 'AAA'), 
    (3, 'A', 'BB', 'AAA'), 
    (4, 'B', 'AA', 'AAA'), 
    (5, 'B', 'AA', 'BBB'), 
    (6, 'B', 'AA', 'CCC'), 
    (7, 'B', 'BB', 'AAA'), 
    (8, 'B', 'CC', 'AAA') 

查詢1

;WITH CTE 
AS 
( 
    SELECT 
     COUNT(Col1) OVER(PARTITION BY col2,col3,col4) AS Counts, 
     T.* 
    FROM 
     @T AS T 
) 
SELECT 
    * 
FROM 
    CTE 
WHERE 
    Counts>1 

結果

2 2 A BB AAA 
2 3 A BB AAA 

QUERY2

;WITH CTE 
AS 
( 
    SELECT 
     ROW_NUMBER() OVER(PARTITION BY col2,col3,col4 ORDER BY col1) AS RowNbr, 
     T.* 
    FROM 
     @T AS T 
) 
SELECT 
    * 
FROM 
    CTE 
WHERE 
    CTE.RowNbr>1 

結果

2 3 A BB AAA 
+0

坦克你,rowNbr是有用的 – forX 2012-04-25 17:25:08

+0

沒問題。記住要記住你認爲很好的答案。這給了我們一種溫暖的模糊感覺:P – Arion 2012-04-25 17:50:32

2

您可以按列,並檢查是否有每組1個多記錄:

select 
    col2, col3, col4 
from 
    MyTable 
group by 
    col2, col3, col4 
having 
    count(*) > 1 

演示:http://www.sqlfiddle.com/#!3/5c3a7/2

+0

坦克你,那麼簡單 – forX 2012-04-25 15:17:05