且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用 OVER 子句删除 SQL Server 中的重复行?

更新时间:2023-02-06 23:05:52

如果您想保留一行重复组,您可以使用 ROW_NUMBER.在此示例中,我保留具有最低 Id 的行:

If you want to keep one row of the duplicate-groups you can use ROW_NUMBER. In this example i keep the row with the lowest Id:

WITH CTE AS 
(
    SELECT rn = ROW_NUMBER() 
                OVER( 
                  PARTITION BY employeeid, dateofincident, typeid, description 
                  ORDER BY Id ASC), * 
    FROM dbo.TableName
) 
DELETE FROM cte 
WHERE  rn > 1