1
+--------------+------------+-------------------+------------+
| id           | DATA_ID    |   SourceID        | DateAdded  |
+--------------+------------+-------------------+------------+
|           1  | 304019032  | 1                 |  2018-01-20|
|           2  | 345583556  | 1                 |  2018-01-21|
|           3  | 299951717  | 3                 |  2018-01-23|
|           4  | 304019032  | 2                 |  2018-01-24|
|           5  | 298519282  | 2                 |  2018-01-24|
|           6  | 299951717  | 3                 |  2018-01-27|
|           7  | 345583556  | 1                 |  2018-01-27|
+--------------+------------+-------------------+------------+

I'm trying to delete duplicate rows that have the same DATA_ID and SourceID, leaving the row with the most recent date.

1
  • Please show which rows you would like to delete. I am guessing you just want to delete rows 1 and 3 based on your description. Commented Jan 27, 2018 at 23:01

2 Answers 2

2

In SQL Server, I like to use row_number() and an updatable CTE for this:

with todelete as (
      select t.*, row_number() over (partition by sourceid, dataid order by dateadded desc) as seqnum
      from t
     )
delete from todelete
    where seqnum > 1;

This will work even when sourceid/dataid is NULL (which is probably not the case for you). It also does not assume that dateadded and id are mutually increasing (although that might be a reasonable assumption).

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

3 Comments

+1 - dateadded could get out of whack with ID if imported from another system and they wanted to retain the original date.
@Gordon Linoff do you mean delete from todelete where seqnum > 1?
@AlexKudryashev . . . LOL. Yes. That would be the more appropriate answer.
0
delete from your_table
where id not in 
(
  select max(id)
  from your_table
  group by data_id, sourceID
)

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.