Deleting duplicate record from table - SQL query

前端 未结 7 1077
有刺的猬
有刺的猬 2021-02-03 15:09

I need to delete duplicate rows only from the table, like I have 3 duplicate rows in the table, my query will delete 2 rows from 3 duplicated rows.

How can I get this? P

7条回答
  •  心在旅途
    2021-02-03 15:36

    This works in SQL Server although it isn't a single statement:

    Declare @cnt int; 
    Select @cnt=COUNT(*) From DupTable Where (Col1=1);  -- Assumes you are trying to delete the duplicates where some condition (e.g. Col1=1) is true.
    Delete Top (@cnt-1) From DupTable
    

    It also doesn't require any extra assumptions (like the existance of another column that makes each row unique). After all, Santanu did say that the rows were duplicates and not just the one column.

    However, the right answer, in my view, is to get a real table structure. That is, add an IDENTITY column to this table so that you can use a single SQL command to do your work. Like this:

    ALTER TABLE dbo.DupTable ADD
        IDCol int NOT NULL IDENTITY (1, 1)
    GO
    

    Then the delete is trivial:

    DELETE FROM DupTable WHERE IDCol NOT IN 
       (SELECT MAX(IDCol) FROM DupTable GROUP BY Col1, Col2, Col3)
    

提交回复
热议问题