Home >Database >Mysql Tutorial >数据库(分组函数)

数据库(分组函数)

WBOY
WBOYOriginal
2016-06-07 15:35:371615browse

分组函数:对表中一组记录进行操作,每次只返回一个结果。 常用的函数有:MIN,MAX,SUM,AVG,COUNT等 MIN和MAX返回每组的最小和最大。 eg:select min(salary),max(salary) from employees; SUM和AVG函数分别返回总和平均。 eg:select sum(salary),avg(salary)

分组函数:对表中一组记录进行操作,每次只返回一个结果。

常用的函数有:MIN,MAX,SUM,AVG,COUNT等


MIN和MAX返回每组的最小值和最大值。

eg:select min(salary),max(salary) from employees;


SUM和AVG函数分别返回总和平均值。

eg:select sum(salary),avg(salary) from emloyees;


count函数主要返回每组的记录条数。

eg:select count(*) from employees  where job_id=' ';


GROUP BY...HAVING 子句的使用。

组函数忽略空值,可以使用NVL,NVL2,COALESCE函数处理空值

eg:相同职位相同经理的员工的平均工资。

select job_id,manager_id,avg(salary) 

from employees

group by job_id,manager_id


*GROUP BY 子句注意问题:

1.GROUP BY 子句后面的列可以不再SELECT 语句中出现。

2.SELECT 子句中出现的 “非分组函数 ” 必须在GROUP BY子句中出现


HAVING子句。

错误示例:

select job_id,max(salary)

from employees

where max(salary)>=8888

group by job_id;

原因是查询语句的执行顺序是:from  where group by select order by


正确示例:

select job_id,max(salary)

from employees

group by job_id

having max(salary)>8888;

总结SELECT语句执行过程:
– 通过FROM子句中找到需要查询的表;
– 通过WHERE子句进行非分组函数筛选判断;
– 通过GROUP BY子句完成分组操作;
– 通过HAVING子句完成组函数筛选判断;
– 通过SELECT子句选择显示的列或表达式及组函数;
– 通过ORDER BY子句进行排序操作。


eg:

select department_id,max(salary)

from employees

where department_id between 30 and 90

group by department_id

having max(salary)>8888

order by max(salary);










Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn