MySQL数据库:第六章:分组函数/聚合函数

回退至Mysql数据库理论与实战
#进阶5:分组函数/聚合函数

本质上就是一种函数,调用语法:select 函数名(实参列表);
函数:
单行函数(常见函数):有几行,最终有几个结果
分组函数(聚合函数):一组中有多行,但最终一个结果,一般用作统计
分组函数:
sum(参数):求和
avg(参数):平均
max(参数):求最大值
min(参数):求最小值
count(参数):统计个数

#1.简单的使用

SELECT SUM(salary),AVG(salary),MAX(salary),MIN(salary),COUNT(salary) FROM employees;

#2.参数支持任意类型?

sum和avg一般用于处理数值型
count、max、min可以处理任意类型

SELECT SUM(last_name),AVG(last_name),MAX(last_name),MIN(last_name),COUNT(last_name) FROM employees;
SELECT SUM(hiredate),AVG(hiredate),MAX(hiredate),MIN(hiredate),COUNT(hiredate) FROM employees;

#3.是否都忽略null值?

五个分组函数都忽略null
SELECT SUM(commission_pct),AVG(commission_pct),MAX(commission_pct),MIN(commission_pct),COUNT(commission_pct) FROM employees;
SELECT AVG(commission_pct),SUM(commission_pct)/107,SUM(commission_pct)/35 FROM employees;

#4.去重的统计

 count(distinct 字段名)
    SELECT COUNT(department_id) FROM employees;
    #案例:员工涉及到了几个部门
    SELECT COUNT(DISTINCT department_id) FROM employees;
    #5.count的实参形式
    SELECT COUNT(*) FROM employees;
    SELECT COUNT(1) FROM employees;
    #6.添加筛选条件
    SELECT COUNT(*)  FROM employees WHERE department_id = 30;
    #7.不是所有的字段都能和分组函数一同查询出来的
    SELECT COUNT(*) ,employee_id FROM employees;