Database knowledge: differences between where, group by, and having

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.