在实际应用中我们会遇到如下的场景:
这时我们就可以使用 group by 语句来解决这类需求。从字面上来理解,group by 表示根据某种规则对数据进行分组,他必须配合聚合函数进行使用,对数据进行分组后可以进行 count、sum、avg、max 和 min 运算。语法如下:
SELECT column_name, aggregate_function(column_name)
FROM table_name
GROUP BY column_name
TIP: aggregate_function:表示聚合函数 group by :可以对一列或者多列进行分组
例如:
select sex, count(*) from student group by sex;
select class, count(*) from student group by class;
select dept,sum(salary) from employee group by dept;
在 SQL 中增加 HAVING 子句原因是, WHERE 关键子无法与聚合函数一起使用。 HAVING 子句可以对分组后的各组数据进行筛选。语法如下:
SELECT column_name,aggregate_funtion(column_name)
FROM table_name
WHERE column_name operator value
GROUP BY column_name
HAVING aggregate_function(column_name) operator value
例如:
select class,count(*) from student group by class having count(*)<30
select dept,max(salary) from employee group by dept having max(salary)>5000