How can I delete duplicate rows in a table

后端 未结 13 1394
情歌与酒
情歌与酒 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条回答
  •  臣服心动
    2020-12-08 23:23

    Here's another way, with test data

    create table #table1 (colWithDupes1 int, colWithDupes2 int)
    insert into #table1
    (colWithDupes1, colWithDupes2)
    Select 1, 2 union all
    Select 1, 2 union all
    Select 2, 2 union all
    Select 3, 4 union all
    Select 3, 4 union all
    Select 3, 4 union all
    Select 4, 2 union all
    Select 4, 2 
    
    
    select * from #table1
    
    set rowcount 1
    select 1
    
    while @@rowcount > 0
    delete #table1  where 1 < (select count(*) from #table1 a2 
       where #table1.colWithDupes1 = a2.colWithDupes1
    and #table1.colWithDupes2 = a2.colWithDupes2
    )
    
    set rowcount 0
    
    select * from #table1
    

提交回复
热议问题