代码之家  ›  专栏  ›  技术社区  ›  Tony_Henrich

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

  •  2
  • Tony_Henrich  · 技术社区  · 15 年前

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

    下面的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'
    
    2 回复  |  直到 15 年前
        1
  •  2
  •   Sam Saffron James Allen    15 年前

    这工作:

    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
    

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

        2
  •  4
  •   Remus Rusanu    15 年前

    就像学术练习一样:

    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提出的解决方案表现得更好。