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
 how to get duplicate row without PK ?

Author  Topic 

java148
Yak Posting Veteran

63 Posts

Posted - 2011-12-16 : 15:57:03
how to get duplicate row without PK ?


create table t1 (name varchar(20), age int) -- no PK
insert into t1 values('john', 20);
insert into t1 values('john', 20);
insert into t1 values('peter', 20);

'john' is duplicate in the table. how to get this out ?

I have coded a version, it works, want to know if we have a concise method.

select ROW_NUMBER() over(order by name) as row, name, age
into #tmp1
from t1

select * from #tmp1

select ROW_NUMBER() over(order by name) as row, name, age
into #tmp2
from t1

select * from #tmp2

select distinct t1.name, t1.age from #tmp1 t1 cross join #tmp2 t2
where t1.row != t2.row
and t1.name = t2.name
and t1.age = t2.age

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2011-12-16 : 16:18:13
select * from (
select ROW_NUMBER() over(order by name) as rowid, name, age
from t1) t
where rowid = 1

Tara Kizer
Microsoft MVP for Windows Server System - SQL Server
http://weblogs.sqlteam.com/tarad/

Subscribe to my blog
Go to Top of Page

java148
Yak Posting Veteran

63 Posts

Posted - 2011-12-16 : 16:32:18
Your version doesn't work.

if we add another row, we can't get 'peter' out.


insert into t1 values('peter', 20);
Go to Top of Page

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2011-12-16 : 16:37:45
Oops, you have to add the partition by to the row_number function. Take a look at example C: http://msdn.microsoft.com/en-us/library/ms186734.aspx

Tara Kizer
Microsoft MVP for Windows Server System - SQL Server
http://weblogs.sqlteam.com/tarad/

Subscribe to my blog
Go to Top of Page
   

- Advertisement -