sql – 删除基于列上相同值的重复记录并保持最新

我想删除基于它们在某个列中具有相同值的重复记录,并在下面的示例中保留一个基于InsertedDate的最新记录.我想要一个不使用游标但基于设置的解决方案.目标:删除所有重复项并保持最新状态.

下面的ddl创建了一些重复项.需要删除的记录是:John1& John2,因为它们与John3具有相同的ID,而John3是最新的记录.

记录John5也需要删除,因为还有另一条ID为3且更新的记录(John6).

Create table dbo.TestTable (ID int,InsertedDate DateTime,Name varchar(50))

Insert into dbo.TestTable Select 1,'07/01/2009','John1'
Insert into dbo.TestTable Select 1,'07/02/2009','John2'
Insert into dbo.TestTable Select 1,'07/03/2009','John3'
Insert into dbo.TestTable Select 2,'John4'
Insert into dbo.TestTable Select 3,'07/05/2009','John5'
Insert into dbo.TestTable Select 3,'07/06/2009','John6'

解决方法

这有效:

delete t 
from TestTable t
left join 
(
    select id,InsertedDate = max(InsertedDate) from TestTable
    group by id
) as sub on sub.id = t.id and sub.InsertedDate = t.InsertedDate
where sub.id is null

如果你必须处理关系,它会变得有点棘手.

dawei

【声明】:淮南站长网内容转载自互联网,其相关言论仅代表作者个人观点绝非权威,不代表本站立场。如您发现内容存在版权问题,请提交相关链接至邮箱:bqsm@foxmail.com,我们将及时予以处理。