删除非唯一id的行。

5

我有一个数据库备份,其中一些记录没有唯一的ID。

一些记录有唯一的ID。 一些具有重复ID的记录包含不同的DateCreated值。 一些具有重复ID的记录包含相同的DateCreated值。

我正在尝试编写一个MSSql 2005查询,只保留具有最新DateCreated值的唯一ID值。

来自:

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

帮助

2个回答

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

即,删除任何存在另一个具有相同id和较晚创建日期的行的行。


1
create table #t ( id int, date datetime )

insert #t 
values(1, getdate())

insert #t 
values(1, getdate()+1)

insert #t 
values(1, getdate()-1)

insert #t 
values(2, getdate())

insert #t 
values(2, getdate()+1)

delete t 
from #t t
left join (select id, min(date) as date from #t group by id) as t1 
    on t.id = t1.id and t1.date = t.date
where t1.date is null

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接