各位用户为了找寻关于MySQL必备基础之分组函数 聚合函数 分组查询详解的资料费劲了很多周折。这里教程网为您整理了关于MySQL必备基础之分组函数 聚合函数 分组查询详解的相关资料,仅供查阅,以下为您介绍关于MySQL必备基础之分组函数 聚合函数 分组查询详解的详细内容

一、简单使用

sum:求和(一般用于处理数值型) avg:平均(一般用于处理数值型) max:最大(也可以用于处理字符串和日期) min:最小(也可以用于处理字符串和日期) count:数量(统计非空值的数据个数)

以上分组函数都忽略空null值的数据

? 1 2 select sum(salary) as 和,avg(salary) as 平均,max(salary) as 最大,min(salary) as 最小,count(salary) as 数量 from employees;

二、搭配distinct去重

(以上函数均可)

? 1 2 select sum(distinct salary) as 和,avg(distinct salary) as 平均,count( distinct salary) as 去重数量,count(salary) as 不去重数量 from employees;

三、count()详细介绍

? 1 2 3 #相当于统计行数方式一 select count(*) from employees; ? 1 2 3 #相当于统计行数方式二,其中1可以用其他常量或字段替换 select count(1) from employees;

效率问题: myisam存储引擎下,count(*)的效率高 innodb存储引擎下,count(*)count(1)的效率差不多,比count(字段)

因此一般用count(*)统计行数

四、分组查询

? 1 2 3 4 5 6 #其中[]内为可选 select 分组函数,列表(要求出现在 group by 的后面) from [where 筛选条件] group by 分组列表 [order by 子句]

示例:

? 1 2 3 4 #查询每个工种的最高工资 select max(salary) as 最高工资,job_id from employees group by job_id;

? 1 2 3 4 5 #查询每个部门中,邮箱包含a的员工的平均工资(分组前的筛选) select avg(salary) as 平均工资,department_id from employees where email like '%a%' group by department_id;

? 1 2 3 4 5 6 #查询部门员工数量大于2的部门的员工数量(分组后的筛选) #使用having select count(*) as 员工数量,department_id from employees group by department_id having count(*)>2;

? 1 2 3 4 #按照多字段 select count(*) as 员工数量,job_id,department_id from employees group by job_id,department_id;

? 1 2 3 4 5 6 7 #完整结构 select avg(salary) as 平均工资,department_id from employees where department_id is not null group by department_id having avg(salary)>9000 order by avg(salary) desc;

到此这篇关于mysql必备基础之分组函数 聚合函数 分组查询详解的文章就介绍到这了,更多相关mysql 分组函数 内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

原文链接:https://blog.csdn.net/m0_46653805/article/details/120731863