How to delete duplicate rows in SQL Server?

后端 未结 23 1393
长情又很酷
长情又很酷 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:55

    I would prefer CTE for deleting duplicate rows from sql server table

    strongly recommend to follow this article ::http://codaffection.com/sql-server-article/delete-duplicate-rows-in-sql-server/

    by keeping original

    WITH CTE AS
    (
    SELECT *,ROW_NUMBER() OVER (PARTITION BY col1,col2,col3 ORDER BY col1,col2,col3) AS RN
    FROM MyTable
    )
    
    DELETE FROM CTE WHERE RN<>1
    

    without keeping original

    WITH CTE AS
    (SELECT *,R=RANK() OVER (ORDER BY col1,col2,col3)
    FROM MyTable)
     
    DELETE CTE
    WHERE R IN (SELECT R FROM CTE GROUP BY R HAVING COUNT(*)>1)
    

提交回复
热议问题