1. The principle of group query
such as:
In a table, there are three semesters of people's test information. Now we want to query the number of people in each semester. At this time, we use select ---- from --- where will generate code redundancy, which is the garbage code we usually say. At this time, we will use the group by keyword.
2. Single column grouping query
Syntax: eg:
select column name, aggregate function from table name select count (*) as number, grade as grade
where constraints from Student
group by column grouped by group
order by column name
note:
The select table can only contain:
(1) Grouped columns
(2) An expression that returns a value for each group, such as an aggregate function
3. Multi-column grouping query
Syntax: eg:
select column name 1, column name 2, aggregate function from table name select count (*) as number of people, grade as grade, sex as gender
where constraints from Student
group by Grouped column name 1, column name 2 group by grade, sex
order by The column name to be sorted order by ----
note:
(1) Single column query does not require order by multi-column query try to add order by
(2) Multi-column query grouping and sorting, the default is to sort the next one
4. Group screening (having):
Syntax: eg:
select ----- from table name select count (*) as number of people, grade as grade
where ------ from Student
group by ------ group by grade
having ------- having count(*)>15
5. How to get a grade with a total number of more than 15 people, the address contains Shanghai
select count (* ) as number of people, grade as grade from Student
where address like'%上海%'
group by grade
having count(*)>15
6. The difference between where and having:
(1) Location:
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 the grouped results