MySql的常用函数2
2.分组函数
功能:做统计使用(统计函数、聚合函数、组函数)
分类:
sum求和、avg平均值、max最大值、min最小值、count计算个数
#1.简单的使用
select sum(salary) from employee ; //返回一个总和
select avg(salary) from employee ; //返回工资平均值
select min(salary) from employee ; //返回最小值
select max(salary) from employee ; //返回最大值
select count(salary) from employee ; //返回总共多少个salary数据
#2.参数类型支持哪些类型
1.sum、avg一般用于处理数值
max、min、count可以处理任何类型
2.分组函数都忽略null值
3.可以和distinct搭配使用,去重
select sum(distinct salary) from employee ;
#3.count函数的详细介绍
select count (*) from employee ; //计数所有非空的列
select count (1) from employee ; //相当于增加1列1,统计1的个数
myisam存储引导下 ,count(*)的效率高
innodb存储引导下,count(*)和count(1)效率差不多,但比count(字段)效率高
#4.和分组函数一同查询的字段有限制
#5.进阶group by
select 分组函数,列(要求出现在group by后面)
from 表
where 筛选条件
group by 分组的列表
order by 子句
#例子,查询最高工资
select max(salary) , job_id
from employee
group by job_id;
#例子,查询每个位置上的部门个数
select count(*),location _id
from department
group by location_id;
#添加筛选条件
#例子,查询邮箱中包含a字符的,每个部门的平均工资
select avg(salary),department_id
from employee
where email like '%a%'
group by department_id
#例子:查询哪个部门的员工个数>2,添加分组后的筛选
1查询每个部门的员工个数
2.根据1的结果筛选
select count(*),departmeng_id
from employee
group by department_id
having count(*)>2;
#按表达式或函数分组
#案例:按员工姓名的长度分组,查询一组员工个数,筛选员工个数>5的有哪些
group by和having 后面支持用别名
select count(*) c,length(last_name) len_name
from employee
group by len_name ;
having c>5;
#按多个字段分组,添加排序
#例子,查询每个部门每个工种的平均工资,按工资高低排序
select avg(salary),department_id,job_id
from employee
where department_ids is not null;
group by department_id,job_id;
having avg(salary)>10000
order by avg(salary) desc;
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】