Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting duplicate record in SQL Server

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?

like image 223
Developer Avatar asked Feb 24 '13 16:02

Developer


People also ask

How do you delete duplicate records in SQL Server?

1) First identify the rows those satisfy the definition of duplicate and insert them into temp table, say #tableAll . 2) Select non-duplicate(single-rows) or distinct rows into temp table say #tableUnique. 3) Delete from source table joining #tableAll to delete the duplicates.

How do I delete duplicate rows in SQL Server w3schools?

To remove duplicates, use the drop_duplicates() method.

How do I delete duplicate rows in SQL based on one column?

How to Eliminate Duplicate Values Based on Only One Column of the Table in SQL? In SQL, some rows contain duplicate entries in a column. For deleting such rows, we need to use the DELETE keyword along with self-joining the table with itself.


1 Answers

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
like image 123
Ian Preston Avatar answered Sep 19 '22 01:09

Ian Preston