Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MS SQL - find and delete duplicities [duplicate]

Tags:

sql

sql-server

Possible Duplicate:
SQL - How can I remove duplicate rows?
SQL query to delete duplicate rows from same table?

How to find duplicity for example in this table?

enter image description here

Column A is unique ID and columns E and F are irrelevant, so rows 1,2,3 and rows 4,5 are duplicates

like image 245
gaffcz Avatar asked Dec 09 '11 08:12

gaffcz


People also ask

How find and delete duplicates in SQL?

SQL Delete Duplicate Rows using Group By and Having Clause According to Delete Duplicate Rows in SQL, for finding duplicate rows, you need to use the SQL GROUP BY clause. The COUNT function can be used to verify the occurrence of a row using the Group by clause, which groups data according to the given columns.

How do I remove duplicate values from a column in SQL?

To remove the duplicate columns we use the DISTINCT operator in the SELECT statement as follows: Syntax: SELECT DISTINCT column1, column2, ...


3 Answers

I have a more effective solution:

DELETE FROM MyTable 
    WHERE A NOT IN 
        (SELECT MIN(A) 
         FROM MyTable GROUP BY B, C, D
        );

Attention: this works if "A" is not NULL. So, for some similar tasks it won't help.

like image 59
Gangnus Avatar answered Sep 21 '22 16:09

Gangnus


Try:

select count(A) Occurrence, B, C, D from TableName group by B, C, D having count(A) > 1

To get the IDs of the duplicated Columns use:

select A from TableName where (B + ' ' + C + ' ' + D) in (select B + ' ' + C + ' ' + D from TableName group by B, C, D having count(A) > 1)

like image 24
CloudyMarble Avatar answered Sep 24 '22 16:09

CloudyMarble


select MyTable.A 
from MyTable 
     join (select B,C,D 
           from MyTable 
           group by B,C,D 
           having Count(*)>1) as T2 on MyTable.B = T2.B 
                                       and MyTable.C = T2.C 
                                       and MyTable.D = T2.D
like image 40
Ravaut123 Avatar answered Sep 22 '22 16:09

Ravaut123