MySQL基础--常见函数之分组函数

一、分组函数

1.功能:用作统计使用,又称为聚合函数或组函数
2.分类:
sum:求和,avg:平均值,max:最大值,min:最小值,count:计算个数

SELECT SUM(salary),AVG(salary) 平均,MIN(salary) 最低,MAX(salary) 最高,COUNT(salary) 个数 
FROM employees;

3.特点:

  • sum、avg一般用于处理数值型
    max、min、count可以处理任何类型
SELECT SUM(last_name),AVG(last_name) FROM employees;#无意义
SELECT SUM(hiredate),AVG(hiredate) FROM employees;#无意义

SELECT MAX(last_name),MIN(last_name) FROM employees;

SELECT MAX(hiredate),MIN(hiredate) FROM employees;

SELECT COUNT(commission_pct) FROM employees;#35
SELECT COUNT(last_name) FROM employees;#107
  • 以上分组函数都忽略null值
SELECT MAX(commission_pct),MIN(commission_pct) FROM employees;# 0.4  0.1
  • 可以和distinct搭配实现去重的运算
SELECT COUNT(DISTINCT salary),COUNT(salary)FROM employees;#57  107
  • count函数的详细介绍:一般使用COUNT(*)用作统计行数

效率:
MYISAM存储引擎下,COUNT()的效率最高
INNODB存储引擎下,COUNT(
)和COUNT(1)的效率差不多,比COUNT(字段)要高(有筛选的过程)

SELECT COUNT(salary) FROM employees;#107

SELECT COUNT(*) FROM employees;#107

SELECT COUNT(1) FROM employees;#107
  • 和分组函数一同查询的字段要求是group by后的字段

二、案例

  1. 查询公司员工工资的最大值,最小值,平均值,总和
SELECT MAX(salary) max_salary,MIN(salary) min_salary,AVG(salary) avg_salary,SUM(salary) sum_salary 
FROM employees;
  1. 查询员工表中的最大入职时间和最小入职时间的相差天数(DIFFERENCE)
SELECT DATEDIFF(MAX(hiredate),MIN(hiredate)) DIFFERENCE
FROM employees;#8735
  1. 查询部门编号为90的员工个数
SELECT COUNT(*) 个数
FROM employees
WHERE department_id = 90;#3

你可能感兴趣的:(MySQL,mysql)