How can I delete duplicate rows in a table

后端 未结 13 1397
情歌与酒
情歌与酒 2020-12-08 22:30

I have a table with say 3 columns. There\'s no primary key so there can be duplicate rows. I need to just keep one and delete the others. Any idea how to do this is Sql Serv

13条回答
  •  旧时难觅i
    2020-12-08 23:02

    This is a way to do it with Common Table Expressions, CTE. It involves no loops, no new columns or anything and won't cause any unwanted triggers to fire (due to deletes+inserts).

    Inspired by this article.

    CREATE TABLE #temp (i INT)
    
    INSERT INTO #temp VALUES (1)
    INSERT INTO #temp VALUES (1)
    INSERT INTO #temp VALUES (2)
    INSERT INTO #temp VALUES (3)
    INSERT INTO #temp VALUES (3)
    INSERT INTO #temp VALUES (4)
    
    SELECT * FROM #temp
    
    ;
    WITH [#temp+rowid] AS
    (SELECT ROW_NUMBER() OVER (ORDER BY i ASC) AS ROWID, * FROM #temp)
    DELETE FROM [#temp+rowid] WHERE rowid IN 
    (SELECT MIN(rowid) FROM [#temp+rowid] GROUP BY i HAVING COUNT(*) > 1)
    
    SELECT * FROM #temp
    
    DROP TABLE #temp   
    

提交回复
热议问题