MySQL必备基础之分组函数 聚合函数 分组查询详解

吾爱主题 阅读:134 2024-04-02 08:06:25 评论:0

一、简单使用

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

可以去百度分享获取分享代码输入这里。
声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

【腾讯云】云服务器产品特惠热卖中
搜索
标签列表
    关注我们

    了解等多精彩内容