1. 聚合函数的介绍

聚合函数又叫组函数,通常是对表中的数据进行统计和计算,一般结合分组(group by)来使用,用于统计和计算分组数据。
常用的聚合函数:

  1. count(col): 表示求指定列的总行数
  2. max(col): 表示求指定列的最大值
  3. min(col): 表示求指定列的最小值
  4. sum(col): 表示求指定列的和
  5. avg(col): 表示求指定列的平均值

    2. 求总行数

    1. -- 返回非NULL数据的总行数.
    2. select count(height) from students;
    3. -- 返回总行数,包含null值记录;
    4. select count(*) from students;

    3. 求最大值

    1. -- 查询女生的编号最大值
    2. select max(id) from students where gender = 2;

    4. 求最小值

    1. -- 查询未删除的学生最小编号
    2. select min(id) from students where is_delete = 0;

    5. 求和

    1. -- 查询男生的总身高
    2. select sum(height) from students where gender = 1;
    3. -- 平均身高
    4. select sum(height) / count(*) from students where gender = 1;

    6. 求平均值

    1. -- 求男生的平均身高, 聚合函数不统计null值,平均身高有误
    2. select avg(height) from students where gender = 1;
    3. -- 求男生的平均身高, 包含身高是null
    4. select avg(ifnull(height,0)) from students where gender = 1;
    说明
  • ifnull函数: 表示判断指定字段的值是否为null,如果为空使用自己提供的值。

    7. 聚合函数的特点

  • 聚合函数默认忽略字段为null的记录 要想列值为null的记录也参与计算,必须使用ifnull函数对null值做替换。

    8. 小结

  • count(col): 表示求指定列的总行数

  • max(col): 表示求指定列的最大值
  • min(col): 表示求指定列的最小值
  • sum(col): 表示求指定列的和
  • avg(col): 表示求指定列的平均值