1.Group by is used alone, and the query results show only one record in a group.
SELECT * FROM `employee`; Show results
select * from employee group by sex; Show results
Only two records will be displayed, this value is obviously incorrect, no collection function is used, and the value displayed is only the first data for each group.
If you want to group and display data, consider using itgroup_concat() function,
2.Used with the group_concat() function,The specified field values in each grouping are displayed
Come on
select sex,group_concat(name) from employee group by sex;
Then use the explode and implode functions to extract the data.
3.Used with set functions,Set functions include count(), sum(), avg(), max(), and min().
select *,count(sex) as total from employee group by sex;
4 Used with having "Having conditional expressions", which can limit the output result. Only the result of the conditional expression is displayed. Instance:
[color=white !important]? select sex,count(sex) from employee group by sex having count(sex) >= 3;
Outcome: [color=white !important]?
havingconditional expression" acts on the grouped records.
5.Group by multiple fields
select * from employee from group by sex,score;
The query results are grouped by sex first, and then by score
6 withUse with rollup
Using with rollup will add a record to the end of all records, which is the sum of all the records above | select sex,count(sex) from employee group by sex with rollup;
|
Outcome: [color=white !important]?
| sex | count(sex) Female | 1 Male | 5 null | 6
|
If it is a string, for example, the name will generate a result of the type "Zhang San, Li Si, Wang Wu", that is, the sum of names.
|