分组函数:也称之为组函数或者聚合函数, oracle提供的常用的分组函数有:sum, avg, count, max, min
1 统计员工总数
1
select count(empno) from emp;
2 统计工种总数
1 2
select count(job) from emp; select count(distinct job) from emp;
3 求员工的平均工资
1
select avg(sal) from emp;
4 求员工的平均奖金
1
select avg(comm), sum(comm)/count(comm), sum(comm)/count(empno) from emp;
5 求员工表中最高工资和最低工资
1
select max(sal), min(sal) from emp;
6 如何去掉分组函数的滤空功能呢?? --提示: nvl函数
1
select count(nvl(empno)) from emp;
结论: 分组函数具有滤空功能.
分组数据: 借助execl理解分组功能.
1 2
基本格式 : select ..., count() from emp where ... group by .. 说明: 按照group by 后给定的表达式,将from后面的table进行分组, 针对每一组, 使用组函数。
1 统计各个部门的平均工资?
1
select deptno, avg(sal) from emp group by deptno;
2 统计各个部门不同工种的平均工资?
1 2 3 4 5 6
select deptno, job, avg(sal) from emp group by deptno, job;
结论: 请思考通过案例1和案例2得出什么样的结论?? select后面的列和group后面的列有什么关系? select a, b, c.., count(f) from table group by a, b, c select后面没有出现在分组函数中的列名, 一定要出现在group by子句中. 在group by子句中出现的列, 不要求一定出现在select后面的列中
3 统计各个部门平均工资高于2000?
1 2 3
select deptno, avg(sal) from emp group by deptno having avg(sal)>2000; 结论:对分组数据进行过滤, 不能够使用where, 应该使用having
4 求10号部门员工的平均薪水
1 2 3 4 5 6 7 8 9 10 11 12 13
方法1: select deptno,avg(sal) from emp where deptno=10 group by deptno;
方法2: select deptno,avg(sal) from emp group by deptno having deptno=10;
结论:比较两种方法, 应该优先使用那种方法?? 第一种方法比第二种方法效率高,原因是第一种是先过滤然后再分组 第二种方法是先处理大量的数据,然后再过滤 使用分组函数统计分组数据不当的情况: select deptno job avg(sal) from emp group by deptno //出错 select deptno avg(sal) from emp group by deptno,job //没有意义