MySQL-分组函数

041-分组函数

重点:所有的分组函数都是自动忽略NULL的
分组函数的执行原则:先分组,然后对每一组数据执行分组函数。如果没有分组语句group by的话,整张表的数据自成一组。

分组函数包括五个:

  • max:最大值
  • min:最小值
  • avg:平均值
  • sum:求和
  • count:计数
sql 复制代码
select sum(sal) from emp;
select lower(ename) from emp;
select max(sal) from emp;
select sum(comm) from emp;
select count(comm) from emp; 统计这个字段当中不为空的个数
select count(*) from emp; 统计表中共有多少条记录(表中的总行数)


分组函数不能直接使用在where子句当中

select ename,job from emp where sal > avg(sal); 这个会报错的

原因:分组的行为是在where执行之后才开始的。

sql 复制代码
select ename, sal from emp where sal>avg(sal);



找出每个岗位的平均薪资

sql 复制代码
select job, avg(sal) from emp group by job;


找出每个部门不同岗位的平均薪资

sql 复制代码
select deptno, job, avg(sal) from emp group by deptno, job;

044-分组查询having

找出除20部分之外,其它部门的平均薪资

sql 复制代码
select deptno, avg(sal) from emp group by deptno having deptno<>20;
select deptno, avg(sal) from emp where deptno<>20 group by deptno;


查询每个部门平均薪资,找出平均薪资高于2000的。

sql 复制代码
select deptno, avg(sal) from emp group by deptno having avg(sal)>2000;

045-分组查询之组内排序

sql 复制代码
select substring_index('http://www.baidu.com','.',1);
select substring_index('http://www.baidu.com','.',2);

不同工作岗位的员工编号按照工资降序排列

sql 复制代码
select group_concat(empno order by sal desc) from emp group by job;


找出每个工作岗位的工资排名在前两名的

sql 复制代码
select substring_index(group_concat(empno order by sal desc),',',2) from emp group by job;

总结单表的DQL语句

select ...5

from ...1

where ...2

group by ...3

having ...4

order by ...6

重点掌握一个完整的DQL语句执行顺序。

相关推荐
captain37612 小时前
MyBatis(入门5)其他查询操作
java·数据库·spring boot·mybatis
小此方13 小时前
Re:Mysql数据库基础篇(八):详细讲解复合查询、多表查询、自连接、多行、多列子查询与合并查询
数据库·mysql
xszivvvv13 小时前
Mariadb数据库frm文件异常,如何恢复数据
数据库·mariadb
smile_life_13 小时前
MySQL 设置 防止账户被暴力破解
数据库·mysql
ShineWinsu14 小时前
对于Qt:QRadioButton常见属性以及QButtonGroup的解析
数据库·c++·qt·microsoft·gui·qradiobutton·qbuttongroup
测试盐14 小时前
oracle数据库卡顿排查
数据库·oracle
滕州市燕猫虎计算机科技工作室个体工商户14 小时前
MySQL、MVCC、多版本并发控制
数据库·mysql·mvcc·数据库事务
明航咨询-陈老师14 小时前
ITSS运行维护服务能力成熟度认证技术纵深:标准模型、等级路径、2026审核趋势与CS/CMMI对比
服务器·数据库·cmmi
缓慢更新15 小时前
AI 辅助生成单测:从接口定义到用例的流水线
java·服务器·前端·网络·数据库·人工智能
AI小百科15 小时前
向量数据库:AI 的「记忆仓库」是怎么工作的
数据库·人工智能·oracle