How to delete duplicate rows in SQL Server?

后端 未结 23 1406
长情又很酷
长情又很酷 2020-11-22 00:58

How can I delete duplicate rows where no unique row id exists?

My table is

col1  col2 col3 col4 col5 col6 col7
john  1          


        
23条回答
  •  名媛妹妹
    2020-11-22 01:41

    You need to group by the duplicate records according to the field(s), then hold one of the records and delete the rest. For example:

    DELETE prg.Person WHERE Id IN (
    SELECT dublicateRow.Id FROM
    (
    select MIN(Id) MinId, NationalCode
     from  prg.Person group by NationalCode  having count(NationalCode ) > 1
     ) GroupSelect
     JOIN  prg.Person dublicateRow ON dublicateRow.NationalCode = GroupSelect.NationalCode 
     WHERE dublicateRow.Id <> GroupSelect.MinId)
    

提交回复
热议问题