How to delete duplicate rows in SQL Server?

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

    Please see the below way of deletion too.

    Declare @table table
    (col1 varchar(10),col2 int,col3 int, col4 int, col5 int, col6 int, col7 int)
    Insert into @table values 
    ('john',1,1,1,1,1,1),
    ('john',1,1,1,1,1,1),
    ('sally',2,2,2,2,2,2),
    ('sally',2,2,2,2,2,2)
    

    Created a sample table named @table and loaded it with given data.

    Delete  aliasName from (
    Select  *,
            ROW_NUMBER() over (Partition by col1,col2,col3,col4,col5,col6,col7 order by col1) as rowNumber
    From    @table) aliasName 
    Where   rowNumber > 1
    
    Select * from @table
    

    Note: If you are giving all columns in the Partition by part, then order by do not have much significance.

    I know, the question is asked three years ago, and my answer is another version of what Tim has posted, But posting just incase it is helpful for anyone.

提交回复
热议问题