Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 delete dublicate rows

Author  Topic 

pascal_jimi
Posting Yak Master

167 Posts

Posted - 2014-01-27 : 02:10:59
declare @a1 table
(id int not null identity(1,1),
phone decimal(18,0),
adress nvarchar(100))

insert @a1
(phone,adress)
values
(111,'new york')
insert @a1
(phone,adress)
values
(111,'new york')
insert @a1
(phone,adress)
values
(111,'new york')
insert @a1
(phone,adress)
values
(222,'maxico')
insert @a1
(phone,adress)
values
(222,'mexico')

select*from @a1
id phone adress
----------- --------------------------------------- ----------------------------------------------------------------------------------------------------
1 111 new york
2 111 new york
3 111 new york
4 222 maxico
5 222 mexico



select phone,count(phone) as say from @a1 group by phone having count(phone)>1

phone say
--------------------------------------- -----------
111 3
222 2



how can I remove duplicate phone

for exmaple

after delete

select*from @a1


select*from @a1
id phone adress
----------- --------------------------------------- ----------------------------------------------------------------------------------------------------
1 111 new york
4 222 maxico




I wrote this to show for example
in my real table have 50000 rows
and
1751 dublicate rows


http://sql-az.tr.gg/

gecew
Starting Member

10 Posts

Posted - 2014-01-27 : 05:02:26
select * from table t1 where exists (select 'x' from table t2
where t1.phone=t2.phone and t1.id>t2.id)

DELETE t1 from table t1 where exists (select 'x' from table t2 where t1.phone=t2.phone and t1.id>t2.id)
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2014-01-27 : 07:19:03
see below illustration

declare @a1 table
(id int not null identity(1,1),
phone decimal(18,0),
adress nvarchar(100))

insert @a1
(phone,adress)
values
(111,'new york')
insert @a1
(phone,adress)
values
(111,'new york')
insert @a1
(phone,adress)
values
(111,'new york')
insert @a1
(phone,adress)
values
(222,'maxico')
insert @a1
(phone,adress)
values
(222,'mexico')

delete t
from (select row_number() over (partition by phone order by id ) as seq from @a1)t
where seq > 1

select * from @a1


output
----------------------------
id phone adress
----------------------------
1 111 new york
4 222 maxico



------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/
https://www.facebook.com/VmBlogs
Go to Top of Page
   

- Advertisement -