How can I find duplicate entries and delete the oldest ones in SQL?

后端 未结 4 1760
轻奢々
轻奢々 2020-12-18 04:13

I\'ve got a table that has rows that are unique except for one value in one column (let\'s call it \'Name\'). Another column is \'Date\' which is the date it was added to th

4条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-18 04:49

    I Just googled up and found this https://www.sqlshack.com/different-ways-to-sql-delete-duplicate-rows-from-a-sql-table/

    this one seems the easiest to read/understand to me:

    DELETE FROM [SampleDB].[dbo].[Employee]
        WHERE ID NOT IN
        (
            SELECT MAX(ID) AS MaxRecordID
            FROM [SampleDB].[dbo].[Employee]
            GROUP BY [FirstName], 
                     [LastName], 
                     [Country]
        );
    

    in your scenario you can just group by name and select the max date instead of Id

提交回复
热议问题