删除原始记录的重复项

时间:2016-08-11 15:05:38

标签: sql sql-server

我有这个好的SQL代码,它从表中选择/删除重复的记录:

WITH CTE AS(
 SELECT UserId, A, B,
 RN = ROW_NUMBER()OVER(PARTITION BY A, B ORDER BY UserId)
 FROM Users
) SELECT * FROM CTE WHERE RN > 1

但它正在选择没有原始记录的所有重复项。如何选择重复+原件(+1)?

2 个答案:

答案 0 :(得分:5)

我认为您要使用count(*)而不是row_number()

WITH CTE AS (
      SELECT UserId, A, B, COUNT(*) OVER (PARTITION BY A, B) as cnt
      FROM Users
     )
SELECT *
FROM CTE
WHERE CNT > 1;

答案 1 :(得分:0)

如果您希望查看原始记录以及重复记录,您可以自行加入您的CTE:

WITH CTE AS (
     SELECT UserID, A, B, rn=ROW_NUMBER() OVER (PARTITION BY A, B, ORDER BY UserID)
     FROM Users)
SELECT c1.*, c2.*
FROM CTE c1
INNER JOIN CTE c2 ON c1.RN = 1 AND c2.RN > 1