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语句执行顺序。

相关推荐
xcLeigh23 分钟前
IoTDB JDBC 完整使用教程:连接、查询、批处理与字符集配置
开发语言·数据库·qt·iotdb·查询·批处理·连接
chunyublog23 分钟前
数据挖掘环境搭建
数据库
阿洛学长33 分钟前
CSDN、掘金、简书博客文章如何转为Markdown?
运维·数据库·架构·php·持续部署
zuozewei38 分钟前
国产化之达梦数据库性能优化方案
数据库·性能优化
Volunteer Technology1 小时前
Spring AI MCP 案例-WebFlux SSE传输模式 (九)
java·数据库·人工智能·spring
神仙别闹2 小时前
基于Java+MySQL实现(GUI)医院管理系统
java·mysql·oracle
betazhou2 小时前
SQL server数据库镜像同步技术
数据库·sql server·高可用·数据库镜像
mpHH2 小时前
postgresql-分区表
数据库·postgresql
AC赳赳老秦3 小时前
OpenClaw与WPS宏联动:批量执行WPS复杂操作,解决办公表格批量处理难题
java·前端·数据库·自动化·需求分析·deepseek·openclaw