如何从表中删除多行

时间:2017-05-03 04:24:48

标签: sql

这里我有一个包含多个重复行的简单表:

客户

Id   Name 
-----------
1    John
2    John
3    Mick
4    Mick
5    John

我写了一个简单的查询,找不到重复的行:

With EmployeeDuplicat As
(
    Select 
        *, ROW_NUMBER() over(PARTITION BY id ORDER BY id) As RowNum
    From 
        Customer
)
Select * 
From EmployeeDuplicat

返回输出:

Id    Name    RowNum
---------------------
1     John       1
2     John       1
3     Mick       1
4     Mick       1
5     John       1

1 个答案:

答案 0 :(得分:2)

WITH EmployeeDuplicat AS
(
    SELECT 
        *, ROW_NUMBER() OVER (PARTITION BY Name ORDER BY id) AS RowNum
    FROM
        Customer
)
DELETE FROM Customer 
WHERE Id IN (SELECT Id 
             FROM EmployeeDuplicat 
             WHERE RowNum > 1)