02-004 MySQL_基础_常见函数之分组函数与分组查询

分组函数

用作统计使用,又叫做聚合函数或统计函数或组函数。
分类:
sum()求和
avg()平均值
max()最大值
min()最小值
count()计算非空个数

1.简单使用
select sum(salary) ,avg(salary) from employees

2.支持参数类型
sum、avg 支持数值型
max、min、count 支持数值型、字符型、日期型
3.null不参与运算

4.和distinct搭配
sum(distinct salary)
count(distinct salary)

5.count()详细介绍

count(字段)
count(*) 统计行数
count(1)常量相当于多加一列常量1
效率:
MYISAM存储引擎:count(*)最高
InnoDB存储引擎:count(*)和count(1)差不多,比统计字段高

6.补充
和分组函数一起查询的字段一般是group by 后的字段。

分组查询

筛选

和分组函数一起查询的字段一般是group by 后的字段。
1.分组前筛选
select AVG(salary),department_id
from employees
where email like ‘%a%’
group by department_id;
where 在from后group by 前

2.分组后筛选(表里面没有的用having)
select count(*),department_id
from employees
group by department_id
*having count( )>2;

3.结合使用的举例
select min(salary) ,manager_id
from employees
where manager_id > 102
group by manager_id
having min(salary) > 5000;
特点:
分组前筛选数据源是原始表,分组后筛选数据源是分组后的结果集;
分组函数做条件肯定是在having子句中;
能分组前筛选的优先使用分组前筛选;

分组

1.按表达式或函数分组

#按员工姓名长度分组,统计每组个数,个数大于5的
select count(*) ,length(last_name)
from  employees 
group by length(last_name)
having count(*) > 5

2.按多个字段查询
select AVG(salary),department_id,job_id
from employees
group by department_id,job_id;
字段无顺序限制

3.添加排序
select AVG(salary),department_id,job_id
from employees
group by department_id,job_id
order by AVG(salary) desc;

学习整理于MySQL 基础+高级篇.

发布了53 篇原创文章 · 获赞 0 · 访问量 404

猜你喜欢

转载自blog.csdn.net/weixin_40778497/article/details/103539315