How to delete duplicate rows in SQL Server?

后端 未结 23 1445
长情又很酷
长情又很酷 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:52
    -- this query will keep only one instance of a duplicate record.
    ;WITH cte
         AS (SELECT ROW_NUMBER() OVER (PARTITION BY col1, col2, col3-- based on what? --can be multiple columns
                                           ORDER BY ( SELECT 0)) RN
             FROM   Mytable)
    
    
    
    delete  FROM cte
    WHERE  RN > 1
    
    0 讨论(0)
  • 2020-11-22 01:53
    with myCTE
    as
    
    (
    select productName,ROW_NUMBER() over(PARTITION BY productName order by slno) as Duplicate from productDetails
    )
    Delete from myCTE where Duplicate>1
    
    0 讨论(0)
  • 2020-11-22 01:53
    DELETE FROM TBL1  WHERE ID  IN
    (SELECT ID FROM TBL1  a WHERE ID!=
    (select MAX(ID) from TBL1  where DUPVAL=a.DUPVAL 
    group by DUPVAL
    having count(DUPVAL)>1))
    
    0 讨论(0)
  • 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)
    
    0 讨论(0)
  • 2020-11-22 01:58
    DECLARE @TB TABLE(NAME VARCHAR(100));
    INSERT INTO @TB VALUES ('Red'),('Red'),('Green'),('Blue'),('White'),('White')
    --**Delete by Rank**
    ;WITH CTE AS(SELECT NAME,DENSE_RANK() OVER (PARTITION BY NAME ORDER BY NEWID()) ID FROM @TB)
    DELETE FROM CTE WHERE ID>1
    SELECT NAME FROM @TB;
    --**Delete by Row Number** 
    ;WITH CTE AS(SELECT NAME,ROW_NUMBER() OVER (PARTITION BY NAME ORDER BY NAME) ID FROM @TB)
    DELETE FROM CTE WHERE ID>1;
    SELECT NAME FROM @TB;
    
    0 讨论(0)
提交回复
热议问题