Share six ways for SQL Server to delete duplicate rows

Source: Internet
Author: User

1. If an ID field exists, it is a unique field.
Copy codeThe Code is as follows:
Delect table where id not in (
Select max (id) from table group by col1, col2, col3...
)

The field followed by the group by clause is the condition for you to judge repetition. For example, if only col1 is used, if the content of col1 is the same, the record is the same.

2. This can also be used to determine all fields.
Copy codeThe Code is as follows:
Select * into # aa from table group by id1, id2 ,....
Delete table
Insert into table
Select * from # aa

3. No ID
Copy codeThe Code is as follows:
Select identity (int, 1, 1) as id, * into # temp from tabel
Delect # where id not in (
Select max (id) from # group by col1, col2, col3 ...)
Delect table
Inset into table (...)
Select... from # temp

4. col1 + ',' + col2 + ','... col5 join primary key
Copy codeThe Code is as follows:
Select * from table where col1 + ',' + col2 + ','... col5 in (
Select max (col1 + ',' + col2 + ','... col5) from table
Where having count (*)> 1
Group by col1, col2, col3, col4
)

The field followed by the group by clause is the condition for you to judge repetition. For example, if only col1 is used, if the content of col1 is the same, the record is the same.

5.
Copy codeThe Code is as follows:
Select identity (int, 1, 1) as id, * into # temp from tabel
Select * from # temp where id in (
Select max (id) from # emp where having count (*)> 1 group by col1, col2, col3 ...)

6.
Copy codeThe Code is as follows:
Select distinct * into # temp from tablename
Delete tablename
Go
Insert tablename select * from # temp Sqlclub
Go
Drop table # temp

The preceding describes how SQL Server deletes duplicate rows.

Related Article

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.