Group aggregation and group filtering

Pre: https://blog.csdn.net/Jaihk662/article/details/80150754

Note: All underscore + italic statements are optional statements


Group query:

SQL statement: Select… from…   where…

Group by grouping condition

Application scenarios:


As shown in the table above, you can use Ave() to find the average of all grades, so how to find the average grade of each student ?

The statement and result are as follows: select st , avg(score) from sc

group by st;


Text description: All tuples are grouped by student number, and the average score is calculated for each group


Group filtering:

Function: Conditional filtering of sets (ie grouping), that is, the sets/groups that meet the conditions are left, and the sets/groups that do not meet the conditions are eliminated

SQL statement: Select… from…   where…

Group by grouping condition having grouping filter condition

Application scenarios:

Still the above table (sc), you now know how to find the average score of all students, so how to find the average score of passing courses for students with more than two passing courses ? need to filter the group

The statement and result are as follows:


Text description: First pick out all the tuples with scores >= 60 from the table, and then group them by st. For any group, if the number of tuples in the group is >= 2, then keep it, otherwise delete the entire group , then find the average score for the reserved group

Example ②:

It is easy to notice that the above is " the average grade of the passing courses of the students who meet the conditions"

Instead of " the average grade of all the courses of the students who meet the conditions", how to find the latter?

The statement and result are as follows:


word description:

Step 1: First pick out all tuples with scores >= 60 from the table, and then group them by st. For any group, if the number of tuples in the group is >= 2, then keep it, otherwise delete the entire group , then the remaining tuples map out all the student numbers

Step 2: Pick out all the student IDs from the table that belong to the legal student IDs in the subquery, and find the average score


Attachment: The difference between the having clause and the where clause expressing conditions:



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325831218&siteId=291194637