SQL statement used to delete duplicate records

Source: Internet
Author: User
Tags lenovo

How can I delete duplicate data when there are duplicate records in the database table?

Of course, the premise is the repeated definition: In the database table, we think that one or more fields are the same, then we think this record is repeated.

See the following table:

Rowid Dep_id Dep_name Company
Aaarj4aaeaaabegaaa 13 Personnel Department Lenovo 2
Aaarj4aaeaaabeiaaa 11 R & D department Baidu Hahahaha
Aaarj4aaeaaabeiaab 12 Personnel Department Lenovo 1

In this table, I think the record with duplicate dep_name is repeated. I want to delete the Redundant Personnel Department and keep only one Personnel Department.

The SQL statement is as follows:

Select D. rowid from lsy_department D/* Delete from lsy_department D */
Where D. rowid in
(
Select rowid from lsy_department C
Where C. dep_name in
(
Select a. dep_name from lsy_department
Where 1 = 1
Group by dep_name
Having count (A. dep_name)> 1
)
) And D. rowid not in
(
Select min (T. rowid) from lsy_department t
Where 1 = 1
Group by T. dep_name
Having count (*)> 1
)

Rowid
Aaarj4aaeaaabeiaab

Change the first line to delete.

 

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.