sql双倍多列密钥

时间:2012-04-25 15:09:53

标签: sql-server sql-server-2005

它是一个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 个答案:

答案 0 :(得分:2)

您可以按列进行分组,并检查每个组的记录是否超过1条:

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

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

答案 1 :(得分: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