Delete duplicates from SQL Server table

Hi Experts,
I'd like to delete duplicates from a SQL Server table. This is the query to show the duplicates:

SELECT Emp_Id, COUNT(Emp_Id) FROM TrainingLocal Where CourseId='164' GROUP BY Emp_Id HAVING COUNT(Emp_Id)>1

Would you please help me write a query that deletes the duplicates from this table?
I would really appreciate your help
romsomIT DeveloperAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Scott PletcherSenior DBACommented:
;WITH cte_dups AS (
    SELECT Emp_Id, ROW_NUMBER() OVER(PARTITION BY Emp_Id ORDER BY (SELECT NULL)) AS row_num
    FROM TrainingLocal
    WHERE CourseId='164'
)
DELETE FROM cte_dups
WHERE row_num > 1

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
romsomIT DeveloperAuthor Commented:
Thank you so much, this is perfect!
Doug BishopDatabase DeveloperCommented:
; WITH cteDups AS (
SELECT ROW_NUMBER() OVER (PARTITION BY Emp_Id ORDER BY BY Emp_Id) as RowNum,
               Emp_Id
FROM TrainingLocal 
Where CourseId='164')

DELETE cteDups WHERE RowNum > 1

Open in new window

Protecting & Securing Your Critical Data

Considering 93 percent of companies file for bankruptcy within 12 months of a disaster that blocked access to their data for 10 days or more, planning for the worst is just smart business. Learn how Acronis Backup integrates security at every stage

Scott PletcherSenior DBACommented:
You're welcome!
aranaCommented:
With CTE_Duplicates as
   (select Emp_Id, row_number() over(partition by empid order by empid) rownumber 
   from TrainingLocal Where CourseId='164' )
   delete from CTE_Duplicates where rownumber!=1
   

Open in new window


or
DELETE DUP
FROM
(
 SELECT ROW_NUMBER() OVER (PARTITION BY Emp_Id ORDER BY Emp_Id) AS Val
 FROM TrainingLocal Where CourseId='164' 
) DUP
WHERE DUP.Val > 1

Open in new window

romsomIT DeveloperAuthor Commented:
Thank you everyone for your quick and helpful responses!
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
SQL

From novice to tech pro — start learning today.