二、分组函数
功能:用作统计使用,又称为聚合函数或统计函数或组函数
分类:
①SUM:求和
②AVG:求平均值
③MAX:求最大值
④MIN:求最小值
⑤COUNT:计算个数
特点:
①SUM和AVG仅支持数值型参数
②MAX、MIN支持可比较的参数
③COUNT支持任何类型的参数,但只计数非空的值
④所有分组函数都忽略NULL值,对于为NULL的字段不参与运算
⑤与DISTINCT搭配使用实现去重
⑥COUNT最常用
⑦和分组函数一同查询的字段要求是GROUP BY后的字段
效率:
5.5以前的存储引擎MYISAM:COUNT(*)的效率最高
5.5以后的存储引擎INNODB:COUNT(1)与COUNT(*)效率大致相同 > COUNT(字段)#1、简单使用
USE myemployees;
SELECT SUM(salary) FROM employees;
SELECT AVG(salary) FROM employees;
SELECT MAX(salary) FROM employees;
SELECT MIN(salary) FROM employees;
SELECT COUNT(salary) FROM employees; #计算salary字段非空的值有多少个
SELECT SUM(salary) 和,ROUND(AVG(salary),2) 平均,MAX(salary) 最大
FROM employees;
#2、参数支持哪些类型
#sum和avg仅支持数值型参数,max、min支持可比较的参数,count支持任何类型的参数,但只计数非空的值
SELECT SUM(last_name),AVG(last_name)
FROM employees;
SELECT MAX(last_name),MIN(last_name),COUNT(last_name)
FROM employees;
#3、是否忽略null值
SELECT SUM(commission_pct),AVG(commission_pct),SUM(commission_pct)/35,SUM(commission_pct)/107
FROM employees;
SELECT MAX(commission_pct),MIN(commission_pct),COUNT(commission_pct)
FROM employees;
#4、与distinct搭配
SELECT SUM(salary),SUM(DISTINCT salary)
FROM employees;
SELECT COUNT(DISTINCT commission_pct) #去重前107,后7
FROM employees;
SELECT COUNT(DISTINCT salary) #去重前107,后57
FROM employees;
SELECT AVG(salary),AVG(DISTINCT salary) #去重前6461.682243,去重后6461.682243
FROM employees;
SELECT MIN(salary),MIN(DISTINCT salary) #去重前2100.00,去重后2100.00
FROM employees;
#5、count函数的详细介绍
SELECT COUNT(salary) FROM employees;
SELECT COUNT(*) FROM employees;
#统计任何非空列(只要有字段不为空)==查询表的总行数
SELECT COUNT(1) FROM employees;
#相当于给每一行的最后插入一个字段,字段的值均为1,count统计1的个数==查询表的总行数
SELECT COUNT(i) FROM employees;
#相当于给每一行的最后插入一个字段,字段的值均为i这个常量,count统计1的个数==查询表的总行数
#6、和分组函数一同查询的字段有限制
SELECT AVG(salary),job_id
FROM employees;
#练习
1. 查询各 job_id 的员工工资的最大值,最小值,平均值,总和
SELECT job_id,MAX(salary),MIN(salary),ROUND(AVG(salary),2),SUM(salary)
FROM employees;
2. 查询员工最高工资和最低工资的差距(DIFFERENCE)
SELECT MAX(salary)-MIN(salary) devalue
FROM employees;
3.查询最大入职时间和最小入职时间的相差天数(difference)
#datediff(expr1,expr2) 计算日期expr1与expr2之间相差的天数
SELECT DATEDIFF('2020-03-07','1972-12-10');
SELECT DATEDIFF(MAX(hiredate),MIN(hiredate)) difference
FROM employees;
4.查询部门编号为90的员工个数
SELECT department_id,COUNT(*) AS 数量
FROM employees
WHERE department_id=90;