SQL Server Forums
Profile | Register | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 Remove Duplicates
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

Anouar
Starting Member

Denmark
8 Posts

Posted - 03/04/2013 :  10:11:04  Show Profile  Reply with Quote
Hi all,

I want to remove some duplicates from a table.

The structure of the table is as follows:

ID, Contact, School

And the duplicates are listed as follows:

1 Bob 200
2 Bob 200
3 Jim 10
4 John 30
5 Wang 40
6 Wang 40

Any help would be highly appreciated

Best Regards
Anouar

TG
Flowing Fount of Yak Knowledge

USA
6059 Posts

Posted - 03/04/2013 :  10:30:44  Show Profile  Reply with Quote
Assuming that (Contact, School) constitute your logical key then this should work. You can run the SELECT first and if you like the results then run the DELETE.

select t.*
--delete t
from   (
       select contact, school, min(id) idToKeep
       from   <table>
       group by contact, school
       having count(*) > 1
       ) dupes
inner join <table> t
       on t.contact = dupes.contact
       and t.school = dupes.school
where  t.id > dupes.idToKeep


Once that is done then you should put a UNIQUE constraint on the table to prevent more duplicate values.


Be One with the Optimizer
TG
Go to Top of Page

Anouar
Starting Member

Denmark
8 Posts

Posted - 03/05/2013 :  06:55:19  Show Profile  Reply with Quote
Thank you that works like a charm.

Best Regards
Anouar
Go to Top of Page
  Previous Topic Topic Next Topic  
 New Topic  Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.09 seconds. Powered By: Snitz Forums 2000