keruilin
keruilin

Reputation: 17512

Return duplicate records

I simply want to return duplicate records from a table. In my case, a record is duplicate if more than one record has the same value in col1, col2, col3, and col4.

Upvotes: 3

Views: 1063

Answers (2)

Quassnoi
Quassnoi

Reputation: 425291

SELECT  m.*
FROM    (
        SELECT  col1, col2, col3, col4, COUNT(*)
        FROM    mytable
        GROUP BY
                col1, col2, col3, col4
        HAVING  COUNT(*) > 1
        ) md
JOIN    mytable m
ON      m.col1 = md.col1
        AND m.col2 = md.col2
        AND m.col3 = md.col3
        AND m.col4 = md.col4

Upvotes: 1

ypercubeᵀᴹ
ypercubeᵀᴹ

Reputation: 115520

SELECT col1, col2, col3, col4
     , COUNT(*) AS cnt
FROM yourTable
GROUP BY col1, col2, col3, col4
HAVING COUNT(*) > 1

If there are additional columns that you want to be shown, you can JOIN the above to the table:

SELECT t.*
     , dup.cnt
FROM yourTable t
    JOIN
      ( SELECT col1, col2, col3, col4
             , COUNT(*) AS cnt
        FROM yourTable
        GROUP BY col1, col2, col3, col4
        HAVING COUNT(*) > 1
      ) AS dup
      ON  t.col1 = dup.col1
      AND t.col2 = dup.col2
      AND t.col3 = dup.col3
      AND t.col4 = dup.col4

Upvotes: 5

Related Questions