sql – 删除基于列上相同值的重复记录并保持最新
发布时间:2021-01-29 05:30:42 所属栏目:MsSql教程 来源:网络整理
导读:我想删除基于它们在某个列中具有相同值的重复记录,并在下面的示例中保留一个基于InsertedDate的最新记录.我想要一个不使用游标但基于设置的解决方案.目标:删除所有重复项并保持最新状态. 下面的ddl创建了一些重复项.需要删除的记录是:John1 John2,因为它们
我想删除基于它们在某个列中具有相同值的重复记录,并在下面的示例中保留一个基于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 如果你必须处理关系,它会变得有点棘手. (编辑:威海站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |