Usage of distinct in sqlserver (non-Repeated Records)

Source: Internet
Author: User

Let's take a look at the example below:

Table

Field 1 Field 2
Id name
1
2 B
3 c
4 c
5 B

The library structure is like this. This is just a simple example, and the actual situation is much more complicated.

For example, if you want to use a statement to query all data with no duplicate names, you must

Use distinct to remove redundant duplicate records.

Select distinct name from table
The result is:

----------

Name
A

C

It seems that the effect has been achieved, but what I want to get is the id value? Modify the query statement:

Select distinct name, id from table

The result is:

----------

Id name
1
2 B
3 c
4 c
5 B

How does distinct not work? The role is played, but he has two roles at the same time.

Fields, that is, they must have the same id and name to be excluded.

Modify the query statement again:

Select id, distinct name from table

Unfortunately, you cannot get anything except the error message. You must start with distinct. Is it difficult to place distinct in the where condition? Yes. An error is returned.

--------------------------------------------------------

The following method is feasible:

Select *, count (distinct name) from table group by name

Result:

Id name count (distinct name)
1 a 1
2 B 1
3 c 1

The last item is redundant, so you don't have to worry about it.

Group by must be placed before order by and limit. Otherwise, an error will be reported.

 

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.