2016-08-11 135 views
1

我有一個選擇/從表中刪除重複記錄這一良好的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)?

回答

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; 
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