MySQL常用的聚合函数(比较常用滴~)

① 常用的聚合函数

count(col): 表示求指定列的总行数

max(col): 表示求指定列的最大值

min(col): 表示求指定列的最小值

sum(col): 表示求指定列的和

avg(col): 表示求指定列的平均值

② 求总行数

-- 返回非NULL数据的总行数

sql 复制代码
select count(height) from students;

-- 返回总行数,包含null值记录

sql 复制代码
select count(*) from students;

③ 求最大值

-- 查询女生的编号最大值

sql 复制代码
select max(id) from students where gender = 2;

④ 求最小值

-- 查询未删除的学生最小编号

sql 复制代码
select min(id) from students where is_delete = 0;

⑤ 求和

-- 查询男生的总身高

sql 复制代码
select sum(height) from students where gender = 1;

-- 平均身高

sql 复制代码
select sum(height) / count(*) from students where gender = 1;

⑥ 求平均值

-- 求男生的平均身高, 聚合函数不统计null值,平均身高有误

sql 复制代码
select avg(height) from students where gender = 1;

-- 求男生的平均身高, 包含身高是null的

sql 复制代码
select avg(ifnull(height,0)) from students where gender = 1;

说明:ifnull函数:表示判断指定字段的值是否为null,如果为空使用自己提供的值

-----聚合函数的特点-----

聚合函数默认忽略字段为null的记录 要想列值为null的记录也参与计算,必须使用ifnull函数对null值做替换(详情请看第⑥的第二个例子即可,就在上面一点)

相关推荐
骄马之死3 小时前
SpringMVC + SpringBoot 核心知识点总结
java·spring boot·后端
AOwhisky3 小时前
MySQL 学习笔记(第四期):SQL 语言之多表查询
linux·运维·网络·数据库·笔记·学习·mysql
小红卒4 小时前
mysql之udf提权
数据库·mysql·网络安全
郑洁文4 小时前
基于Spring Boot的流浪动物救助网站
java·spring boot·后端·毕设·流浪动物救助
Trouvaille ~4 小时前
【Redis篇】Redis 哨兵(Sentinel):高可用自动故障转移
数据库·redis·缓存·中间件·sentinel·高可用·哨兵
qfljg4 小时前
oracle 迁移到postgres
数据库·oracle
rockey6275 小时前
基于AScript的SQL脚本语言发布啦!
sql·c#·.net·script·expression·动态脚本
螺丝钉code5 小时前
JAVA项目 Claude code CLAUDE.md 到底应该怎么写
java·人工智能·claude code
giaz14n9X5 小时前
Redis 分布式锁进阶第五十七篇
数据库·redis·分布式
剑神一笑5 小时前
Linux ls 命令深度解析:从目录遍历到颜色输出的实现原理
linux·服务器·数据库