且构网

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

如何删除sql server中的重复行?

更新时间:2023-01-20 14:32:10

像CTEs和 ROW_NUMBER 两个组合允许我们查看哪些行被删除(或更新),因此只需更改 DELETE FROM CTE ... SELECT * FROM CTE

I like CTEs and ROW_NUMBER as the two combined allow us to see which rows are deleted (or updated), therefore just change the DELETE FROM CTE... to SELECT * FROM CTE:

WITH CTE AS(
   SELECT [col1], [col2], [col3], [col4], [col5], [col6], [col7],
       RN = ROW_NUMBER()OVER(PARTITION BY col1 ORDER BY col1)
   FROM dbo.Table1
)
DELETE FROM CTE WHERE RN > 1

演示 (结果不同,我认为这是由于您的错字)

DEMO (result is different; I assume that it's due to a typo on your part)

COL1    COL2    COL3    COL4    COL5    COL6    COL7
john    1        1       1       1       1       1
sally   2        2       2       2       2       2

此示例由 col1 单列确定重复$ c> PARTITION BY col1 。如果要包含多个列,只需将它们添加到 PARTITION BY 中:

This example determines duplicates by a single column col1 because of the PARTITION BY col1. If you want to include multiple columns simply add them to the PARTITION BY:

ROW_NUMBER()OVER(PARTITION BY Col1, Col2, ... ORDER BY OrderColumn)