2017-08-21 97 views
0

我都試過,如果每一個ID列的一個條目,刪除重複項保持不可

delete from Student where FirstName in 
(
    select FirstName from 
    (
    select FirstName, 
    row_number() over(partition by FirstName order by FirstName) as rn 
    from Student 
    ) Student 
    WHERE rn > 1 
); 

但其都刪除重複記錄。 請糾正我的查詢。 在此先感謝。

+0

標籤您正在使用的數據庫管理系統! – jarlh

+0

有表主鍵? –

+0

MS SQL SERVER ........ –

回答

2

您可以使用CTE

WITH MyCTE 
    AS 
    (
     SELECT [FirstName], ROW_NUMBER() OVER(PARTITION BY FirstName ORDER BY FirstName) RN 
     FROM Student 
    ) 
    DELETE FROM MyCTE WHERE RN > 1; 
    SELECT * FROM Students; 
+0

我覺得你需要「;」之前用WITH –

+0

其工作表示感謝。 –

0

你根據名字刪除,因此它將從表中刪除所有記錄,嘗試這樣就行了。

Live Demo

WITH StudentCte 
As 
(
SELECT FirstName, ROW_NUMBER() OVER(Partition by FirstName ORDER BY (SELECT NULL)) as RowNum 
FROM Student 
) 

DELETE FROM StudentCte WHERE RowNum > 1; 

SELECT * 
From Student; 
+0

再次非常感謝。 –