How to keep only one row of a table, removing duplicate rows?

前端 未结 8 1598
小蘑菇
小蘑菇 2020-12-08 16:41

I have a table that has a lot of duplicates in the Name column. I\'d like to only keep one row for each.

The following lists the duplicates, but I don\'t know how to

8条回答
  •  独厮守ぢ
    2020-12-08 16:59

    If we want to see first which rows you are about to delete. Then delete them.

    with MYCTE as (
        SELECT DuplicateKey1
            ,DuplicateKey2 --optional
            ,count(*) X
        FROM MyTable
        group by DuplicateKey1, DuplicateKey2
        having count(*) > 1
    ) 
    SELECT E.*
    FROM MyTable E
    JOIN MYCTE cte
    ON E.DuplicateKey1=cte.DuplicateKey1
        AND E.DuplicateKey2=cte.DuplicateKey2
    ORDER BY E.DuplicateKey1, E.DuplicateKey2, CreatedAt
    

    Full example at http://developer.azurewebsites.net/2014/09/better-sql-group-by-find-duplicate-data/

提交回复
热议问题