It is well known that group by a field is grouped according to this field, so what is the result of group by multiple fields? The preceding conclusion analogy can be obtained, group by followed by multiple sub-segments are grouped according to multiple fields
Note: The following examples are found on the Internet and are for informational purposes only:
For example, there is a student selection schedule, the table structure is as follows:
Table:subject_selection
Subject |
Semester |
Attendee |
ITB001 |
1 |
John |
ITB001 |
1 |
Bob |
ITB001 |
1 |
Mickey |
ITB001 |
2 |
Jenny |
ITB001 |
2 |
James |
MKB114 |
1 |
John |
MKB114 |
1 |
Erica |
We want to count the number of students enrolled in each course and apply the following SQL:
SELECT Subject, Count(*)FROM Subject_SelectionGROUP BY Subject
The following results are obtained:
Subject |
Count |
ITB001 |
5 |
MKB114 |
2 |
Because the table records there are 5 students choose itb001,2 A student chose MKB114.
So group by X, y?
Group by X, y means that all records with the same X field value and Y field value are placed in a group.
Example: Ask for statistics on how many people choose each semester in each discipline, and apply the following SQL:
SELECT Subject, Semester, Count(*)FROM Subject_SelectionGROUP BY Subject, Semester
The above SQL means to group the data in the Subject_selection table, place records with the same subject and semester field values in the same grouping, and then apply the aggregate function to the data in each group (count,sum, AVG, etc).
The resulting results are:
Subject |
Semester |
Count |
ITB001 |
1 |
3 |
ITB001 |
2 |
2 |
MKB114 |
1 |
2 |
From the records in the table we can see that the result of this grouping is correct. There were 3 students who chose ITB001 in the first semester, 2 students chose ITB001 in the second semester,
There were two students who chose MKB114 in the first semester and no one chose MKB114 in the second semester.
Another example is an order form, which records all the orders that have been paid in the table.
Table:order
Product |
Buyer |
spending |
PD001 |
Todd |
12.00 |
PD001 |
Todd |
12.00 |
PD001 |
Todd |
12.00 |
PD001 |
Lily |
12.00 |
PD001 |
Lily |
12.00 |
PD002 |
Todd |
20.00 |
PD002 |
Todd |
20.00 |
Now we want to count how much each user spends on each item and execute the following SQL
SELECT Product,Buyer, SUM(Spending)FROM `Order`GROUP BY Product, Buyer
The results obtained are as follows:
Product |
Buyer |
SUM |
PD001 |
Todd |
36.00 |
PD001 |
Lily |
24.00 |
PD002 |
Todd |
40.00 |
This article refers to: MYSQL Group by groups multiple fields
If you want to reprint please specify the Source: https://www.cnblogs.com/zhuchenglin/p/9732612.html
Group by multiple fields