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.
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.
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.
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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With