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
:
(我喜欢CTE和ROW_NUMBER
因为两者结合使我们能够看到删除(或更新)了哪些行,因此只需将DELETE FROM CTE...
更改为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
This example determines duplicates by a single column col1
because of the PARTITION BY col1
.
(由于PARTITION BY col1
本示例通过单个列col1
确定重复项。)
If you want to include multiple columns simply add them to the PARTITION BY
: (如果要包括多个列,只需将它们添加到PARTITION BY
:)
ROW_NUMBER()OVER(PARTITION BY Col1, Col2, ... ORDER BY OrderColumn)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…