Tuesday, February 14, 2012

Delete older entries with duplicate names

Assume I have the following table.

id name
-- ----
1 John
2 Josh
3 Mike
4 John
5 Dana
6 Josh
7 John

I want to delete the older entries of the duplicate names. So in this instance, I want to delete id 1, 2 and 4.

Thanks ahead of time...drop table table1
go
create table table1(id int
,iname varchar(10))
go
insert table1 select 1,'John'
insert table1 select 2,'John'
insert table1 select 3,'Mike'
insert table1 select 4,'John'
insert table1 select 5,'Dana'
insert table1 select 6,'Josh'
insert table1 select 7,'John'
go
select *
--delete
from table1
where iname in (select iname from table1 group by iname having count(*)>1)
and id not in (select max(id) from table1 group by iname having count(*)>1)|||Is there not a way to do it programmatically without defining which names to re-insert? I have a few hundred rows of duplicates|||Originally posted by jiggle it
Is there not a way to do it programmatically without defining which names to re-insert? I have a few hundred rows of duplicates
What do you mean "to re-insert"? Just run last query and all older reconds for duplicates will be gone. ;)|||I found the answer

http://aspfaqs.com/aspfaqs/ShowFAQ.asp?FAQID=186|||DELETE Table1
WHERE id IN
(SELECT A.id from Table1 A, Table1 B
WHERE A.name = B.name
AND A.id < B.id)

May not be as efficient but requires less typing, which is a plus in my book )

No comments:

Post a Comment