5. 分组函数
分组函数导图
功能:用作统计使用,又称为聚合函数或统计函数或组函数。
分类:sun求和、avg平均值、max最大值、 min最小值、 count计算个数
语法:select sum(字段名) from 表 ;
特点:
- 一般用于处理数值类型
- 以上函数都忽略null值
- 可以和distinct关键字搭配使用,实现去重除运算。
-
count(*)
:统计元组的个数 -
count(列名)
:计算一列中值得个数 -
sum(列名)
:计算一列值的总和 -
max(列名)
:求一列值的最大值 -
min(列名)
:求一列值的最小值 -
去重:distinct
count(distinct custcity) :去重查统计custcity列中的项的个数
简单的使用
-
求一下工资之和
select sum(salary) from employees;
-
同理
select avg(salary) from employees;
select min(salary) from employees;
select max(salary) from employees;
select count(salary) from employees;
-
可以同时放多个
select sum(salary) , avg(salary) , min(salary) , max(salary) , count(salary) from employees;
-
叠加其他函数使用
select round(sum(salary)) from employees;
将工资求和的结果保留两位小数。 -
参数的支持类型
一般只支持数字类型,但是放入字符类型也不会报错,而是输出0,但是不提倡放入字符类型。 -
忽略null值
比如求和的时候算平均的时候,null值是不参与运算的。(null值加任何数都等于null) -
和distinct搭配,去重再运算
select sum(salary) from employees;
所有数求和
select sum(distinct salary) from employees;
去重之后再求和
其他的也可以像sum这样去重之后再进行运算。 -
count的函数的详细介绍
统计employees数据库中的所有行数。
select count(*) from employees;
count(*)就表示统计整个数据库
select count(1) from employees;
该语句也会输出和count(*)同样的值是统计数据库的行数,count(1)就表示在数据库的每一行前面都加上1个2,然后统计1的个数,也就是统计数据库的函数。把1换成其他的常量或字符串同理。
myisam存储引擎下,count()的效率最高。
innodb存储引擎下,count()和count(1)的效率差不多,比count(字符)要高一些。
总之用count(*)为最好
例题
-
查询员工表中,最大入职时间和最小入职时间相差天数。
减法函数:datediff(a,b)表示a-b
select datediff(max(hiredate),min(hiredate)) as date from empployees ;
-
查询一下部门编号,为90的员工个数。
select count(*) from employees where department_id =90 ;