#第08章_聚合函数
#1.常见的几个聚合函数
#1.1 AVG \ SUM:只适用于数值类型的字段
#1.2 MAX \ MIN
#1.3 COUNT:
#①:作用:计算指定字段在查询结构中出现的次数
SELECT COUNT(salary),COUNT(department_id),COUNT(1),COUNT(*)
FROM employees;
SELECT *
FROM employees;
#如何计算表中有多少条记录?
#方式1:COUNT(1)
#方式2:COUNT(*)
#方式3:COUNT(具体字段)不一定对
#注意:CONUT()计算时不包含空值null
#公式:AVG() = SUM() / COUNT()
#2. GROUP BY 的使用
#查询各个部门的平均工资:
SELECT department_id,AVG(salary),MAX(salary)
FROM employees
GROUP BY department_id;
#查询各个job_id的平均工资:
SELECT job_id,AVG(salary),MAX(salary)
FROM employees
GROUP BY job_id;
#查询各个department_id,job_id的平均工资:
SELECT department_id,job_id,AVG(salary)
FROM employees
GROUP BY department_id,job_id;
#结论1:SELECT中出现的非组函数的字段必须声明在GROUP BY中
#反之,GROUP BY中的声明字段可以不出现在SELECT中.
#结论2:GROUP BY 声明在FROM WHERE后面,ORDER BY LIMIT前面.
#结论3( 新特性):MySQL中的GROUP BY中使用WITH ROLLUP
SELECT department_id,AVG(salary)
FROM employees
GROUP BY department_id WITH ROLLUP;
SELECT department_id,AVG(salary) "avg_sal"
FROM employees
GROUP BY department_id WITH ROLLUP
ORDER BY avg_sal DESC;
#3.HAVING的使用(用来过滤数据的)
#练习:查询各个部门的最高工资比10000高的部门信息:
#错误的写法:
SELECT department_id ,MAX(salary)
FROM employees
WHERE MAX(salary) > 10000
GROUP BY department_id;
SELECT department_id ,MAX(salary)
FROM employees
WHERE MAX(salary) > 10000
GROUP BY department_id;
#要求1:如果过滤条件中使用了聚合函数,则必须使用HAVING来代替WHERE.否则报错.
#要求2:HAVING必须声明在GROUP BY后面!
#正确的写法:
SELECT department_id ,MAX(salary)
FROM employees
#GROUP BY department_id
HAVING MAX(salary) > 10000;
#开发中使用HAVING的前提就是使用了GROUP BY!
#练习:查询部门id为10,20,30,40这四个部门的最高工资比10000高的部门信息:
#方式1:推荐,执行效率高
SELECT department_id,MAX(salary)
FROM employees
WHERE department_id IN(10,20,30,40)
GROUP BY department_id
HAVING MAX(salary) > 10000;
#方式2:
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中!
/*
WHERE VS HAVING
1.HAVING的适用范围更广
2.如果过滤条件中没有聚合函数时,WHERE效率高.
*/
#4.SQL的底层执行原理:
#4.1SELECT 的完整结构
/*
#sql92语法:
SELECT ...字段1,...字段2,...(存在聚合函数)
FROM ...,...,...
WHERE 多表的连接条件 AND 不包含聚合函数的过滤条件
GROUP BY ...,...
HAVING 包含聚合函数的过滤条件
ORDER BY ...,...(ASC,DESC)
LIMIT ...(分页操作)
#sql99语法:
SELECT ...字段1,...字段2,...(存在聚合函数)
FROM ...(LEFT / RIGHT)JOIN...ON 多表的连接条件
(LEFT / RIGHT)JOIN...ON 多表的连接条件
WHERE 不包含聚合函数的过滤条件
GROUP BY ...,...
HAVING 包含聚合函数的过滤条件
ORDER BY ...,...(ASC,DESC)
LIMIT ...(分页操作)
*/
#4.2 SQL语句的执行过程:
/*
# 执行顺序:2
SELECT ...字段1,...字段2,...(存在聚合函数)
# 执行顺序:1
FROM ...(LEFT / RIGHT)JOIN...ON 多表的连接条件
(LEFT / RIGHT)JOIN...ON 多表的连接条件
WHERE 不包含聚合函数的过滤条件
GROUP BY ...,...
HAVING 包含聚合函数的过滤条件
# 执行顺序:3
ORDER BY ...,...(ASC,DESC)
LIMIT ...(分页操作)
*/