MySQL-分组函数

作者 : admin 本文共1143个字,预计阅读时间需要3分钟 发布时间: 2024-06-16 共1人阅读

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

  • max:最大值
  • min:最小值
  • avg:平均值
  • sum:求和
  • count:计数
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; 统计表中共有多少条记录(表中的总行数)

MySQL-分组函数插图
分组函数不能直接使用在where子句当中
select ename,job from emp where sal > avg(sal); 这个会报错的
原因:分组的行为是在where执行之后才开始的。

select ename, sal from emp where sal>avg(sal);

MySQL-分组函数插图(1)
MySQL-分组函数插图(2)
找出每个岗位的平均薪资

select job, avg(sal) from emp group by job;

MySQL-分组函数插图(3)
找出每个部门不同岗位的平均薪资

select deptno, job, avg(sal) from emp group by deptno, job;

MySQL-分组函数插图(4)

044-分组查询having

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

select deptno, avg(sal) from emp group by deptno having deptno20;
select deptno, avg(sal) from emp where deptno20 group by deptno;

MySQL-分组函数插图(5)
查询每个部门平均薪资,找出平均薪资高于2000的。

select deptno, avg(sal) from emp group by deptno having avg(sal)>2000;

MySQL-分组函数插图(6)

045-分组查询之组内排序

select substring_index('http://www.baidu.com','.',1);
select substring_index('http://www.baidu.com','.',2);

MySQL-分组函数插图(7)
不同工作岗位的员工编号按照工资降序排列

select group_concat(empno order by sal desc) from emp group by job;

MySQL-分组函数插图(8)
找出每个工作岗位的工资排名在前两名的

select substring_index(group_concat(empno order by sal desc),',',2) from emp group by job;

MySQL-分组函数插图(9)

总结单表的DQL语句

select …5
from …1
where …2
group by …3
having …4
order by …6
重点掌握一个完整的DQL语句执行顺序。

本站无任何商业行为
个人在线分享 » MySQL-分组函数
E-->