How to remove duplicates from table using SQL query

后端 未结 7 1640
遇见更好的自我
遇见更好的自我 2020-12-17 04:34

I have a table which is as follows:

emp_name   emp_address  sex  matial_status  
uuuu       eee          m    s
iiii       iii          f    s
uuuu       eee         


        
7条回答
  •  难免孤独
    2020-12-17 05:38

    The best answer is here:
    Use this SQL statement to identify the extra duplicated rows:

     select * from Employee a 
    where %%physloc%% >
    (select min(%%physloc%%) from Employee b
    where a.emp_name=b.emp_name and a.emp_address=b.emp_address and a.sex=b.sex);

    you will get the extra row:

    uuuu   eee m   s 


    Use this SQL statement to delete the extra duplicated rows:

     delete from Employee a 
    where %%physloc%% >
    (select min(%%physloc%%) from Employee b
    where a.emp_name=b.emp_name and a.emp_address=b.emp_address and a.sex=b.sex);


    For all duplicated records, only the one with lowest physical location is kept. This method can be applied to remove all kinds of duplicated rows.

    I am assuming that you use MS SQL Server. If you are using Oracle DB, then you can just replace '%%physloc%%' with 'rowid'

    Enjoy the code!

提交回复
热议问题