Mysql中内置的聚合函数:max,min,avg,count,sum。
sum:求和
select sum(列) from table_name [其他子句];
max:求最大值
select max(列) from table_name [其他子句];
min:求最小值
select min(列) from table_name [其他子句];
avg:求平均值
select avg(列) from table_name [其他子句];
count:求数量
select count(列) from table_name [其他子句];
group by
group by 是对数据进行分组,分组时,表中有相同值的分为一组,分组后可以进行聚合查询。
group by 分组后的select查询中,不能出现除了被分组的字段和被聚合的字段。
select 列1, 列2, (聚合函数) from table_name group by 列1, 列2;
having
having是对group by分组后的结果集进行筛选,后面跟的是聚合函数。
select 列1, 列2, (聚合函数) from table_name group by 列1, 列2 having分组后条件;
# 查询部门人数大于2的部门名称和编号
select dept_name,dept_id from dept group by dept_name having count(*) > 2;