Solved

Remove Duplicate record using SQL Query

Posted on 2012-03-27
4
490 Views
Last Modified: 2012-04-05
Hi,

I have a sql table where I want to remove duplicate records. Without using temp table, is there a better way to remove duplicates.

I want to remove emp1 from bucket 12 & wants to keep one emp1 in bucket 12. Also I want to remove emp2 from bucket 16 as emp2 exists in bucket12.

Here is my table

Table1
-----------
   bucketNum    empName
      12           emp1
      12           emp2
      12           emp3
      12           emp1
      16           emp2
      16           emp4


Output
------------
 bucketNum    empName    
      12           emp1
      12           emp2
      12           emp3    
      16           emp4


Thanks
0
Comment
Question by:r_pat72
4 Comments
 
LVL 39

Accepted Solution

by:
appari earned 500 total points
ID: 37774808
try this, take back up of existing data or run it within a transaction and commit after checking the results.
;with data as (Select *, row_number() over(partition by empName order by bucketNum) rowNum from tableName)
delete from data where rowNum > 1

Open in new window

0
 
LVL 20

Expert Comment

by:BuggyCoder
ID: 37775080
here is the list of all possible ways of removing duplicates:-
http://www.simple-talk.com/sql/t-sql-programming/removing-duplicates-from-a-table-in-sql-server/
0
 
LVL 2

Expert Comment

by:ben9
ID: 37778377
"remove emp2 from bucket 16 as emp2 exists in bucket12."

What is your criteria for which one to keep? Do you always keep the lower numbered bucket and consider the others duplicates?
0
 

Author Comment

by:r_pat72
ID: 37779806
yes, want to keep lower number bucket.
0

Featured Post

Efficient way to get backups off site to Azure

This user guide provides instructions on how to deploy and configure both a StoneFly Scale Out NAS Enterprise Cloud Drive virtual machine and Veeam Cloud Connect in the Microsoft Azure Cloud.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article explains how to reset the password of the sa account on a Microsoft SQL Server.  The steps in this article work in SQL 2005, 2008, 2008 R2, 2012, 2014 and 2016.
Ever needed a SQL 2008 Database replicated/mirrored/log shipped on another server but you can't take the downtime inflicted by initial snapshot or disconnect while T-logs are restored or mirror applied? You can use SQL Server Initialize from Backup…
Nobody understands Phishing better than an anti-spam company. That’s why we are providing Phishing Awareness Training to our customers. According to a report by Verizon, only 3% of targeted users report malicious emails to management. With compan…

730 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question