Multiple methods for searching duplicate records in SQL Server databases

Source: Internet
Author: User

Example:Table stuinfo, which has three fields: recno (auto-increment), stuid, and stuname

 

The SQL statement used to create the table is as follows:

 

Create Table [stuinfo] (

[Recno] [int] identity (1, 1) not null,

[Stuid] [varchar] (10) Collate chinese_prc_ci_as not null,

[Stuname] [varchar] (10) Collate chinese_prc_ci_as not null

) On [primary]

Go

 

1. Check the repeated values of one or more columns.(Only the value of the record can be found, and the information of the entire record cannot be found)

For example, you can find records with duplicate stuid and stuname values.

Select stuid, stuname from stuinfo

Group by stuid, stuname

Having (count (*)> 1

 

2. query records with duplicate values in a column(This method is used to identify all duplicate records. If there are two duplicate records, we will find two records)

For example, find the record with duplicate stuid

Select * From stuinfo

Where stuid in (

Select stuid from stuinfo

Group by stuid

Having (count (*)> 1

)

 

3. query records with duplicate values in a column(Only Redundant records are displayed. That is to say, two records are displayed if there are three duplicate records)

Note: A non-repeated column is required. In this example, recno is used.

For example, find the record with duplicate stuid

Select * From stuinfo S1

Where recno not in (

Select max (recno) from stuinfo S2

Where s1.stuid = s2.stuid

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.