1.聚合函数
select ename,job,max(sal) from emp----在没有gruop by的情况下,select 后如果出现了聚合函数,不能加其他字段
select max(sal),avg(sal) from emp
select comm from emp
select avg(comm) from emp----求平均值时,系统会自动过滤空值
select sum(comm) from emp----求和时,系统会自动过滤空值
重点:count()
select count(empno) from emp
select count(mgr) from emp----求个数时,空值不算在内
select count(deptno) from emp----求个数时,重复值也算个数
select count(comm) from emp
select count() from emp
select count(7) from emp
一定要判断清楚count() 括号里面的字段名,尽量不要使用
2、group by
select deptno from emp group by deptno
select DEPTNO from emp group by deptno------错误
group by 后面的列跟select后面的列的关系:
select deptno from emp group by deptno,ename—14
select deptno,count(job) from emp group by deptno,job
要想 select,必须 group by(针对与字段)
注意:不要为了select 而去写group by
select deptno,ename from emp group by deptno,ename
分情况考虑
1)select ename,empno from emp group by ename,empno—不影响结果,可以直接加
2)select ename,max(sal) from emp group by ename----影响结果,不能直接加
select ename,sal from emp where sal=(select max(sal) from emp)
求每个部门,每种工作的员工个数
select deptno,job,count(empno) from emp group by deptno,job
求每个部门的平均工资,最高工资,最低工资,工资总和,工资个数
select deptno,avg(sal),max(sal),min(sal),sum(sal),count(sal) from emp group by deptno
having:对分组之后的数据进行过滤
求最高工资大于1500的部门编号
select deptno from emp group by deptno having max(sal) > 1500
只有出现了group by,才会用到 having
求十号部门平均工资大于1500的工作,查询结果按平均工资降序排列
select job, avg(sal)
from emp
where deptno = 10
group by job
having avg(sal) > 1500
order by 2 desc
总结where和having的区别:
1,where 是对初始数据进行过滤,having是对分组之后的数据进行过滤
2,只有用到了分组,才会使用having,其余情况都用where
select job, avg(sal)
from emp
group by job
having avg(sal) > 1500 and job <> ‘SALESMAN’
order by 2 desc
3,只有聚合函数的条件放在having之后,其余所有条件都放在where之后
—求工作人数大于三人的工种
select job,count(empno) from emp group by job having count(empno)>=4
回顾
select A from B where C group by D having E order by F [asc]/desc
B-C-D-E-A-F
因为有顺序关系,所以注意别名的使用
SELECT AVG(SAL),
CASE WHEN TO_CHAR(HIREDATE,‘YYYY/MM/DD’)<‘1985/01/01’ THEN ‘85年以前’
ELSE ‘85年及以后’
END AS “R”
FROM EMP
GROUP BY R;