【问题标题】:Delete records which are considered duplicates based on same value on a column and keep the newest删除基于列上相同值被视为重复的记录并保留最新的记录
【发布时间】:2009-07-24 08:20:58
【问题描述】:

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

下面的 ddl 创建了一些重复项。需要删除的记录有:John1 & John2,因为它们的ID与John3相同,而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'

【问题讨论】:

    标签: sql sql-server


    【解决方案1】:

    就像一个学术练习:

    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 提出的解决方案性能要好得多。

    【讨论】:

    【解决方案2】:

    这行得通:

    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
    

    如果你必须处理关系,那就有点棘手了。

    【讨论】:

    • 谢谢。在我的情况下,我不会有领带。我选择你的答案是因为我还不熟悉 SQL Server 的新功能。
    猜你喜欢
    • 2019-12-20
    • 2021-03-18
    • 1970-01-01
    • 1970-01-01
    • 2012-04-12
    • 1970-01-01
    • 2015-09-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多