gpt4 book ai didi

sql - 删除基于列上相同值被视为重复的记录并保留最新的记录

转载 作者:行者123 更新时间:2023-12-02 09:01:10 26 4
gpt4 key购买 nike

我想删除因在某一列中具有相同值而被视为重复的记录,并保留根据下面示例中的 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, '07/03/2009', 'John4'
Insert into dbo.TestTable Select 3, '07/05/2009', 'John5'
Insert into dbo.TestTable Select 3, '07/06/2009', 'John6'

最佳答案

就像一项学术练习:

with cte as (
select *, row_number() over (partition by ID order by InsertedDate desc) as rn
from TestTable)
delete from cte
where rn <> 1;

大多数时候,Sam 提出的解决方案性能要好得多。

关于sql - 删除基于列上相同值被视为重复的记录并保留最新的记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1175061/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com