简体   繁体   中英

SQL - find the duplicates

select * from table1 where destination in  ('chi','usa','ind')

Ideally my result set should be 3 rows. one row for each destination.

But in my result there are duplicates.

chi
usa
ind
usa

I want to find which destination is duplicated. I have hundreds of destination and i want to delete the duplicate records. I am not looking for distinct. Am looking for the duplicated ones.

Use group by and having instead of distinct

select destination from table1 
where destination in  ('chi','usa','ind')
group by destination 
having count(*)>1

If you want to delete these and retain one, it gets a little messy. This is probably the shortest way, but its a bit of a hack.

delete from destination where id not in (
    select max(id) from table1
      where destination in  ('chi','usa','ind')
      group by destination 
    ) 

This will give you a count of duplicates, ordered by number of dupes desc:

SELECT CountryAbbr,
       COUNT(*) AS DuplicateCount
FROM   YourTable
GROUP BY CountryAbbr
HAVING COUNT(*) > 1
Order By 2 DESC

Add group by at the end... should give you two columns, on is the country, the other is how many times it was in the list.

So..

select * from table1 where destination in  ('chi','usa','ind') group by destination

Hope this helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM