Oracle之分组函数

来源:互联网 发布:sql exec 编辑:程序博客网 时间:2024/05/01 00:33
1、组函数(1)获取员工表员工的平均工资、工资总和、工资的最大值、工资的最小值以及工资记录数SQL> select avg(sal) 平均工资,sum(sal) 工资总和,max(sal) 最大值,min(sal) 最小值,count(sal) 记录数 2  from emp;  平均工资   工资总和     最大值     最小值     记录数---------- ---------- ---------- ---------- ----------2073.21429      29025       5000        800         14(2)组函数遇到null:求员工的平均奖金<1>三种方式:SQL> select avg(comm) 方式一,sum(comm)/count(comm) 方式二,sum(comm)/count(*) 方式三  2  from emp;    方式一     方式二     方式三---------- ---------- ----------       550        550 157.142857SQL> select count(comm),count(*) from emp;<2>原因:COUNT(COMM)   COUNT(*)----------- ----------          4         14<3>结论:组函数会自动过滤空值<4>解决方案:SQL> select count(nvl(comm,0)),count(*) from emp;COUNT(NVL(COMM,0))   COUNT(*)------------------ ----------                14         142、分组数据(1)求各个部门的平均工资SQL> select deptno,avg(sal) from emp group by deptno;   DEPTNO   AVG(SAL)--------- ----------       30 1566.66667       20       2175       10 2916.66667(2)按不同部门和不同的职位来统计平均工资SQL> select deptno,job,avg(sal),count(deptno)  2  from emp  3  group by deptno,job  4  order by 1;   DEPTNO JOB         AVG(SAL) COUNT(DEPTNO)--------- --------- ---------- -------------       10 CLERK           1300             1       10 MANAGER         2450             1       10 PRESIDENT       5000             1       20 ANALYST         3000             2       20 CLERK            950             2       20 MANAGER         2975             1       30 CLERK            950             1       30 MANAGER         2850             1       30 SALESMAN        1400             4已选择9行。(3)group by的使用要求<1>select检索的列必须要位于group by后面的集合列中(不包含组函数) select a, b, c   from emp   group by a, b, c, d;<2>必须要在分组数据之上, 进行结果集的检索3、分组过滤(1)查询平均工资大于2000的部门SQL> select deptno,avg(sal) from emp  2  group by deptno  3  having avg(sal) > 2000;   DEPTNO   AVG(SAL)--------- ----------       20       2175       10 2916.66667(2)having和where子句的区别<1>求10号部门的平均工资(先分组再过滤)SQL> select deptno,avg(sal) from emp  2  group by deptno  3  having deptno = 10;   DEPTNO   AVG(SAL)--------- ----------       10 2916.66667<2>求10号部门的平均工资(先过滤再分组)SQL> select deptno,avg(sal) from emp  2  where deptno = 10  3  group by deptno;   DEPTNO   AVG(SAL)--------- ----------       10 2916.66667