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值做替换(详情请看第⑥的第二个例子即可,就在上面一点)

相关推荐
majingming1235 小时前
FUNCTION
java·前端·javascript
zopple5 小时前
常见的 Spring 项目目录结构
java·后端·spring
2401_874732536 小时前
为你的Python脚本添加图形界面(GUI)
jvm·数据库·python
stuartevil7 小时前
【MySQL】SQL菜鸟教程(一)
sql·mysql·oracle
Chengbei117 小时前
Redis 图形化综合检测工具:redis_tools_GUI,一键探测 + 利用
数据库·redis·web安全·网络安全·缓存·系统安全
hutengyi7 小时前
PostgreSQL的备份方式
数据库·postgresql
xuxie997 小时前
N11 ARM-irq
java·开发语言
cjy0001117 小时前
springboot的 nacos 配置获取不到导致启动失败及日志不输出问题
java·spring boot·后端
mldlds7 小时前
MySQL加减间隔时间函数DATE_ADD和DATE_SUB的详解
android·数据库·mysql