一.聚合函数
1.sum函数
sum函数用于求和,只能用于数字类型,字符类型统计结果为0;日期类型统计结果为毫秒数相加。
2.max函数/min函数
max函数/min函数用于获得非空值的最大值/最小值。
例:(1)10部和20部中,月收入最高的员工
select max(sal+ifnull(comm,0)) from t_emp where depno IN (10,20)
(2) 员工名字最长的是几个字符
select max(length(ename)) from t_emp
3.AVG函数
avg函数用于获取非空值的平均值,非数字数据统计结果为0;
4.count函数
count(*)函数用于获得包含空值的记录数,count(列名)用于获得包含非空值的记录数。
例:(1)查询10和20部门中,底薪超过2000并且工龄超过15年的员工人数
select count(*) from t_emp
where depno IN(10,20) and sal>=2000
and datediff(now(),hiredate)/365>=15
二、分组
1.group by
group by 子句的作用是通过一定的规则将一个数据集划分为若干个晓得区域,然后针对每个小的区域分别进行数据汇总处理。
数据库知识多列分组条件,执行的时候逐级分组
select deptno,job,count(*),avg(sal)
from t_emp group by deptno,job
order by deptno;
查询语句中如果含有group by 子句,那么select子句中的内容就必须要遵守规定:select子句中可以包括聚合函数,过着group by 子句的分组列,其余内容均不可以出现再select子句中。
2.with rollup
with rollup 对分组结果集再次坐汇总计算
select deptno,count(*),avg(sal),max(sal),min(sal)
from t_emp group by deptno with rollup
3.group_concat
group_concat函数可以把分组查询中的某个字段拼接成一个字符串。
select deptno,group_concat(ename),count(*)
from t_emp where sal>=2000
group by deptno;
4.having 子句
查询每个部门中,1982年以后入职的员工超过两个人的部门编号
select deptno
from t_emp
where hiredate>="1982-01-01"
group by deptno having count(*)>=2;
having子句的特殊用法:按照数字1分组,mysql会根据select子句中的列进行分组,having子句也可以正常使用
select deptno,count(*) from t_emp
group by 1 having deptno IN(10,20);
4.各种子句的执行顺序
from -> where -> group by ->having-> select ->order by ->limit