Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove non-unique ids rows

From a database backup I have records without unique Ids.

Some records have unique IDs. Some records with duplicated IDs contains different DateCreated values. Some records with duplicated IDs contains the same DateCreated values.

I'm trying to get a MSSql 2005 query will leave only unique ID values with the most recent DateCreated value.

From

ID|    DateCreated  
1 |    1/1/09
2 |    1/2/09
2 |    2/2/09
3 |    1/3/09
3 |    1/3/09

To

ID|    DateCreated  
1 |    1/1/09
2 |    2/2/09
3 |    1/3/09

Help

like image 446
sre Avatar asked Mar 03 '09 22:03

sre


1 Answers

DELETE FROM myTable AS t1 
WHERE EXISTS (
    SELECT 1 FROM myTable AS t2 
    WHERE t1.ID=t2.ID AND t1.DateCreated<t2.DateCreated)

ie, delete any row where there is another row with the same id and a later creation date.

like image 200
Khoth Avatar answered Sep 27 '22 23:09

Khoth