Database Structure:
Data Table: Student
Table Structure:
Field name datatype Len
Id INT 20
Name varchar 25
Major varchar 25
Score INT 20
Sex varchar 20
Table data:
No./name/major/credits/Gender
ID name Major score sex
1 Jak Chinese 40 F
2 rain math 89 m
3 Leo PHY 78 F
4 Jak math 76 F
5 rain Chinese 56 m
6 Leo math 97 f
7 Jak PHY 45 f
8 Jak draw 87 F
9 Leo Chinese 45 f
Now we want to get a view:
It is required to query the gender of boys and list the total scores of each student:
SQL:
Select S. *, sum (S. Score) from student s where sex = 'F' group by S. Name
Result:
ID name Major score sex sum (S. Score)
1 Jak Chinese 40 f 248
3 Leo PHY 78 F 220
We can see that there are two groups in total. The two groups of students are Jak and Leo, and each group is the same student, so that we can use the aggregate function.
Only the group by statement can be used to use aggregate functions such as Count () and sum.
Next we will further filter the above results to show only students whose total score is greater than 230:
SQL:
Select S. *, sum (S. Score) from student s where sex = 'F' group by S. Name having sum (S. Score)> 230
Result:
ID name Major score sex sum (S. Score)
1 Jak Chinese 40 f 248
It can be seen that having has almost the same functionality as where.
Conclusion:
1. The WHERE clause is used to filter the rows generated by the operation specified in the from clause.
2. The group by clause is used to group the output of the WHERE clause.
3. The having clause is used to filter rows from grouping results.