MySQL数据库聚合函数(count、max、min、sum、avg) 您所在的位置:网站首页 sql聚合函数不允许出现where MySQL数据库聚合函数(count、max、min、sum、avg)

MySQL数据库聚合函数(count、max、min、sum、avg)

2023-07-03 21:13| 来源: 网络整理| 查看: 265

1. 聚合函数的介绍

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

常用的聚合函数:

count(col): 表示求指定列的总行数     【聚合函数不对空值进行统计】max(col): 表示求指定列的最大值min(col): 表示求指定列的最小值sum(col): 表示求指定列的和avg(col): 表示求指定列的平均值 2. 求总行数 -- 返回非NULL数据的总行数. select count(height) from students; 【不包含空值】 -- 返回总行数,包含null值记录; select count(*) from students; 【包含空值】

 【为了统计不出错,选择id进行统计,count(id),一般用*,id可能不存在】

 【一般如果是指定列名,那么就是主键字段,通用写法是count(*)】

3. 求最大值 -- 查询男生的编号最大值 select max(id) from students where gender = '男';  4. 求最小值 -- 查询男生的编号最小值 select min(id) from students where gender = '男';  5. 求和 -- 查询男生的总身高 select sum(height) from students where gender = '男'; -- 平均身高 select sum(height) / count(*) from students where gender = '男';  6. 求平均值 -- 求男生的平均身高, 聚合函数不统计null值,平均身高有误 select avg(height) from students where gender = '男'; -- 求男生的平均身高, 包含身高是null的 select avg(ifnull(height,0)) from students where gender = '男'; 【首先判断身高是否为空,如果为空的话,赋值为0】

 说明

ifnull函数: 表示判断指定字段的值是否为null,如果为空使用自己提供的值。 7. 聚合函数的特点 聚合函数默认忽略字段为null的记录 要想列值为null的记录也参与计算,必须使用ifnull函数对null值做替换。


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有