单行函数 :一行得一个结果
多行函数 :多行得一个结果 (分组函数,聚合函数)
sum() :对于某个字段中数据进行累加求和,只应用于数值型
avg() :对于某个字段中数据计算平均值 ,只应用于数值型
max() :对于某个字段中的数据求最大值 ,字符型,数值型,日期型
min() :对于某个字段中的数据求最小值
count() :统计行的个数
select * from emp;
-- 查询20号部分的员工的总薪水
select sum(sal)as 总薪水 from emp where deptno=20; -- 只需要告诉mysql做什么,不需要告诉它怎么做
select round(avg(sal))as 平均薪水 from emp where deptno=20;
select max(ename) ,min(ename) from emp; -- 英文字母的升序 字符型
select max(hiredate),min(hiredate) from emp; -- 查询入职时间最晚的和入职时间最早的
-- 想计算入职时间最晚的与入职之间最早的时间差是多少年
select DATEDIFF( max(hiredate),min(hiredate))/365 from emp;
select max(sal) ,min(sal) from emp;
--
select count(*) from emp where deptno=20; -- 建议使用*
select count(1) from emp where deptno=20; -- 也可以,count(常量)
select * from emp where deptno=20;
什么是分组? group by
select * from emp;
-- 查询20号部分的员工的总薪水
select sum(sal)as 总薪水 from emp where deptno=20; -- 只需要告诉mysql做什么,不需要告诉它怎么做
select round(avg(sal))as 平均薪水 from emp where deptno=20;
select max(ename) ,min(ename) from emp; -- 英文字母的升序 字符型
select max(hiredate),min(hiredate) from emp; -- 查询入职时间最晚的和入职时间最早的
-- 想计算入职时间最晚的与入职之间最早的时间差是多少年
select DATEDIFF( max(hiredate),min(hiredate))/365 from emp;
select max(sal) ,min(sal) from emp;
--
select count(*) from emp where deptno=20; -- 建议使用*
select count(1) from emp where deptno=20; -- 也可以,count(常量)
select * from emp where deptno=20;
-- 查询每个部分的总人数
select deptno, count(*) from emp where deptno is not null group by deptno;
-- 查询每个部门的平均薪水
select deptno,avg(sal) from emp where deptno is not null group by deptno;
-- 查询每种职位的平均薪水
select job ,avg(sal) from emp group by job order by avg(sal) desc;
-- select后只能写分组项和分组函数
select job ,avg(sal) from emp group by job order by avg(sal) desc;
select deptno, count(*) from emp where deptno is not null group by deptno
-- 查询每个部分的总人数不低于5人的部门
select deptno, count(*) from emp where deptno is not null group by deptno
having count(*)>5; -- having 是分组之后的条件判断
select deptno, count(*) from emp group by deptno
having deptno is not null;
/**where与having都用于条件判断(筛选条件)
where 应用在group by之前
having 应用在group by之后
非分组函数,只是普通的条件判断,使用where与having结果相同,但是建议使用where
where之后只有是普通的条件判断
having之后可以是普通的条件判断,也可以是分组函数的条件判断
*/
--查询每个部门的总人数
select * from emp order by deptno;
标签:多行,20,函数,sal,emp,MySQL,deptno,where,select
来源: https://blog.csdn.net/HanYueQian/article/details/96561013