How to use distinct in sqlserver
This article shows you how to use distinct in sqlserver. The content is concise and easy to understand. It will definitely brighten your eyes. I hope you can get something through the detailed introduction of this article.
Table table
Field 1 Field 2idname1a2b3c4c5b
The structure of the library is something like this, this is just a simple example, the actual situation will be much more complicated.
For example, if I want to query all the data that name does not repeat with one statement, I must
Use distinct to remove redundant duplicate records.
The results obtained by select distinct name from table are:
-
Nameac
It seems to have achieved results, but what I want to get is the id value? Change the query statement:
Select distinct name, id from table
The result will be:
-
Id name1 a2 b3 c4 c5 b
Why didn't distinct work? It worked, but he did two at the same time.
Fields, that is, fields that must have the same id and name can be excluded.
Let's change the query statement again:
Select id, distinct name from table
Unfortunately, you get nothing but error messages, distinct must be put at the beginning. Is it too difficult to put distinct in the where condition? If you can, you can still report an error.
The following methods are feasible:
Select *, count (distinct name) from table group by name
Results:
Id name count (distinct name) 1 a 12 b 13 c 1
The last item is superfluous, don't worry about it, the goal is achieved.
Group by must be placed before order by and limit, or an error will be reported.
The above is how to use distinct in sqlserver. Have you learned any knowledge or skills? If you want to learn more skills or enrich your knowledge reserve, you are welcome to follow the industry information channel.