一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第13天,点击查看活动详情。
1. 统计函数
count()函数:实现统计表中数据的条数 avg()函数:实现计算字段值的平均值 sum()函数:实现计算字段值的总和 max()函数:实现查询字段值的最大值 min()函数:实现查询字段值的最小值
语法:select function(f1),function(f2)...
from table_name
where 条件(> < and or in is null...)
order by f
limit xx,xx
1.1 count()函数
a count(*) 可以实现对表中数据进行统计,不管是null值还是非null值,全部统计数量。
b count(field) 可以实现对指定的字段进行数量统计,在统计数量时会忽略null值。
例子1:对员工表中,统计员工的人数
select count(*) as num from t_employee;
例子2:对员工表中,统计有奖金的员工人数
select count(comm)
from t_employee
where comm !=0;
where comm <>0;
where not comm=0;
说明:comm列为null和0都是属于没有奖金的
count(comm)忽略comm列的null值
1.2 avg()函数 -- 求平均值
语法:avg(field)对指定字段进行平均值的计算,在计算平均值时会忽略null值
例子:计算员工表中有提成员工的平均值
select avg(comm) from t_employee;
1.3 sum()函数 -- 求总和
语法:sum(field)对指定字段进行总和的计算,忽略null。
例子:计算员工表中工资数量,平均工资,工资总和
select count(sal),avg(sal),sum(sal)
from t_employee;
1.4 max()函数和min()函数
语法:max(field)对指定字段统计最大值,忽略null
min(field)对指定字段统计最小值,忽略null
例子:查询员工表,查询出员工的最高工资和最低工资
select max(sal) maxSal,min(sal) minSal
from t_employee;
强调:在使用count()函数,avg()函数,sum()函数,max()函数和min()函数时,如果表中没有任何的数据记录, count()函数返回0,其它函数返回null。
create table m_test(
id int,
name varchar(20)
);
select count(*) from m_test; --> 0
select count(id) from m_test; --> 0
select sum(id) from m_test; --> null
select max(id) from m_test; --> null