Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TSQL Remove duplicated rows on some column only [duplicate]

Tags:

sql

tsql

Possible Duplicate:
SQL - How can I remove duplicate rows?

Example this is my table:

SiteKey, Name, City

The SiteKey is auto increament, Name is different , but some times 2 Sitekey will have same City.

Example:

1, A , CityA
2, B,  CityB
3, C,  CityA
4, D,  CityF

so I need to remove rows 3, and keep rows 1,2,4 only.

its on SQL 2005 and up.

thanks your help.

like image 590
Ken Le Avatar asked Jul 21 '11 16:07

Ken Le


People also ask

How can I delete rows with duplicate values in one column in SQL?

In SQL, some rows contain duplicate entries in a column. For deleting such rows, we need to use the DELETE keyword along with self-joining the table with itself.

How do you delete the rows which are duplicate don't delete both duplicate records?

We can use the SQL RANK function to remove the duplicate rows as well. SQL RANK function gives unique row ID for each row irrespective of the duplicate row. In the following query, we use a RANK function with the PARTITION BY clause.


2 Answers

Here are 2 ways you can do it.

DELETE t
FROM 
<table> t
WHERE EXISTS 
    (SELECT 1 FROM <table> 
    WHERE t.SiteKey > SiteKey AND t.City = City)


DELETE t
FROM 
<table> t
INNER JOIN <table> t2
ON  t.City = t2.City
AND t.SiteKey > SiteKey
like image 179
t-clausen.dk Avatar answered Nov 05 '22 15:11

t-clausen.dk


This is standard SQL

DELETE
   mytable
WHERE
    SiteKey NOT IN 
    (
    SELECT
       MIN(SiteKey)
    FROM
       Mytable
    GROUP BY
       City
    ) --Don't need 'KeepMe'

Then, add a unique constraint

ALTER TABLE MyTable WITH CHECK ADD
   CONSTRAINT UQ_MyTable_City UNIQUE (City)
like image 23
gbn Avatar answered Nov 05 '22 15:11

gbn