Deleting duplicate record in SQL Server

时光怂恿深爱的人放手 提交于 2019-12-28 04:05:50

问题


I have written a query to remove duplicate records from a table

;WITH a as
(
SELECT Firstname,ROW_NUMBER() OVER(PARTITION by Firstname, empID ORDER BY Firstname) 
AS duplicateRecCount
FROM dbo.tblEmployee
)
--Now Delete Duplicate Records
DELETE FROM tblEmployee
WHERE duplicateRecCount > 1 

But I don't know where I went wrong it is saying

Invalid column name duplicateRecCount

Can someone help me?


回答1:


You need to reference the CTE in the delete statement...

WITH a as
(
SELECT Firstname,ROW_NUMBER() OVER(PARTITION by Firstname, empID ORDER BY Firstname) 
AS duplicateRecCount
FROM dbo.tblEmployee
)
--Now Delete Duplicate Records
DELETE FROM a
WHERE duplicateRecCount > 1



回答2:


 DELETE duplicates FROM
(SELECT ROW_NUMBER() OVER (PARTITION BY firstname, lastname, EMPNO, salary,dept  ORDER BY empno) cnt
 FROM tblEmp)  duplicates
WHERE duplicates.Cnt > 1


来源:https://stackoverflow.com/questions/15053693/deleting-duplicate-record-in-sql-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!