Delete duplicate rows

前端 未结 3 1585
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-14 14:55

I have a table that looks like this

Table1

Id, Name

How can I write a query that delete all rows with duplicate names but kee

3条回答
  •  逝去的感伤
    2021-01-14 15:16

    If you are using SQL Server 2005 or later:

    With Dups As
        (
        Select Id, Name
            , Row_Number() Over ( Partition By Name Order By Id ) As Num
        From Table1
        )
    Delete Table1
    Where Id In (
                Select Id
                From Dups
                Where Num > 1
                )
    

    If using SQL Server 2000 and prior

    Delete Table1
    Where Exists    (
                    Select 1
                    From Table1 As T1
                    Where T1.Name = Table1.Name
                    Having Min( T1.Id ) <> Table1.Id
                    )
    

提交回复
热议问题