聚合函数
Posted 嫚嫚_
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了聚合函数相关的知识,希望对你有一定的参考价值。
# 第八章 聚合函数
-- 1:常见的聚合函数
-- 1.1 AVG/SUM 只用于数值的字符
SELECT AVG(salary),SUM(salary),AVG(salary)*107
FROM employees;
-- 1.2 max /min
SELECT MAX(salary),MIN(salary)
FROM employees;
SELECT MAX(last_name)
FROM employees;
-- 1.3 count 数个数 不包含空值
SELECT COUNT(employee_id),COUNT(salary),COUNT(1)
FROM employees;
-- 2:group by 的使用
# 需求查询各个部门的平均工资
SELECT department_id,AVG(salary)
FROM employees
GROUP BY department_id
SELECT job_id,AVG(salary)
FROM employees
GROUP BY job_id;
# 需求:查询各个department_id,job_id的工资
SELECT department_id dept_id, job_id, SUM(salary)
FROM employees
GROUP BY department_id, job_id ;
-- 3:having的使用(作用:用来过滤数据)
# 要求一:如果过滤条件使用了聚合函数
# 要求二:having必须使用在group by 后面
# 要求三:开发中,我们使用having 的前提是SQL 中使用了GROUP BY
SELECT department_id,MAX(salary)
FROM employees
GROUP BY department_id
HAVING MAX(salary)>10000;
# 练习 查询部门id 为 10,20,30,40这四个部门工资高10000的信息
-- 方式一(推荐)
SELECT department_id,MAX(salary)
FROM employees
WHERE department_id IN(10,20,30,40)
GROUP BY department_id
HAVING MAX(salary)>10000;
-- 方式二
SELECT department_id,MAX(salary)
FROM employees
GROUP BY department_id
HAVING MAX(salary)>10000 AND department_id IN(10,20,30,40);
-- 结论 当过滤条件中有聚合函数时,过滤条件必须声明在HAVING中
-- 结论 当过滤条件中没有聚合函数时,过滤条件必须声明在where中
-- SELECT ... FROM ... WHERE ... GROUP BY ... HAVING ... ORDER BY ... LIMIT...
以上是关于聚合函数的主要内容,如果未能解决你的问题,请参考以下文章