1

I need to remove some duplicate entries from an intersection table.

The table is incredibly badly set up, without primary keys, so I'm having some trouble removing entries which are duplicates.

Here's just a rough overview of the table:

col1    col2
------------
1       70
1       70
1       71

Both columns carry id's, and duplicates breaks stuff.

1
  • you have some good answers here man ? y don't you accept some ? Commented Mar 22, 2014 at 16:12

3 Answers 3

5

You can use RANKING Functions

with cte as
(
select row_number() over(partition by col1,col2 order by col1,col2 )as rowNum
from tableName
)
delete from cte where rowNum>1

SQL FIDDLE DEMO

Sign up to request clarification or add additional context in comments.

2 Comments

could you tell me why partition by col1,col2 suppose if col1 is IDentity then you'd just partition by col1 right ? then order by other col2..iff :)
@VijaykumarHadalgi col1 is not an identity because the sample data shows duplicates for col1. The issue is that there is not unique key on the table currently, and they are checking for duplicates in col1 and col2, so partition by col1, col2 will reset the row_number for every new/non-duplicate pair of col1, col2
1
with t1dups (col1, coldups)
AS (      
select col2, ROW_NUMBER() Over (Partition by col1, col2 order by col2) as dups from t1 )
delete from t1dups where coldups > 1

Comments

1
drop table #t
create table #t(col1 int,col2 int)
insert into #t values(1,70),(1,70),(2,71)
;with cte as
(

select [col1],[col2],rn=row_number() over(partition by col1 order by col2)  from #t
)
delete from cte where rn>1

select * from #t

DEMO

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.