2

I have three columns in my table

KeyName, Number, Data

The data consist of lot of duplicate entries. I need to delete the 1 row from each of the duplicate entries in the table if the "KeyName" and "Data" are repeated. How shall I achieve this is SQL Query .

3
  • 1
    what is your rdbms? Sql Server, Postgres, Mysql ....? Commented Apr 15, 2016 at 16:53
  • What if there are more than two duplicates? Commented Apr 15, 2016 at 16:55
  • Mine is SQL server. I have only few entries which are more than two duplicates. Which i thought of deleting manually. Commented Apr 15, 2016 at 16:58

2 Answers 2

0

This should do it

WITH CTE
    AS (SELECT KeyName
            , Number
            , Data
            , [rn] = ROW_NUMBER() OVER(PARTITION BY KeyName
                                          , Data ORDER BY KeyName
                                                     , Data)
        FROM   yourtable)
     /* UNCOMMENT BELOW TO DELETE */
     --DELETE
    --FROM   CTE
    --WHERE  rn > 1;

    SELECT *
    FROM   CTE
    WHERE  rn > 1;
Sign up to request clarification or add additional context in comments.

1 Comment

This worked thank you
0

You can keep one row for each pair by using row_number():

with todelete as (
      select t.*,
             row_number() over (partition by keyname, data order by (select NULL)) as seqnum
      from t
     )
delete
from todelete
where seqnum > 1;

As with any such operation, you should check first before deleting. This is easy:

with todelete as (
      select t.*,
             row_number() over (partition by keyname, data order by (select NULL)) as seqnum
      from t
     )
select *
from todelete
where seqnum > 1;

2 Comments

Just received correct answer as yours. Sorry stackoverflow doesnt allow two answers to be marked as correct .Thank you for your response
@arun . . . The decision of which answer to accept is wholly up to the OP.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.