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

相关推荐
counting money22 分钟前
Spring框架基础(配置篇)
java·后端·spring
Irene199133 分钟前
大数据开发语境下,SQL 模式名,映射关系 - - 概念理解
大数据·数据库·sql
顾随37 分钟前
(二)kettle--输入与输出
javascript·数据库·kettle
2401_8330336240 分钟前
如何修复固定定位头部容器中悬浮下拉菜单的错位问题
jvm·数据库·python
SelectDB1 小时前
Doris & SelectDB for AI 实战:从基础 RAG 到知识图谱增强的完整实现
数据库·人工智能·数据分析
秋91 小时前
OceanBase与GreatSQL在Java应用中的性能调优方法有哪些?
java·开发语言·oceanbase
z4424753261 小时前
CSS Grid布局如何实现网格项目的自动增长_设置grid-auto-flow- row
jvm·数据库·python
河野笑生1 小时前
MySQL 范式和反范式详解
数据库
m0_740352421 小时前
如何在 SvelteKit 中为动态加载的图片实现响应式悬停覆盖层
jvm·数据库·python
今天又在写代码1 小时前
并发问题解决
java·开发语言·数据库