天天看点

oracle学习笔记(十):多行函数

1、count():该函数用于统计数量;

统计 emp 表中员工总人数;

注意:* 号适用于表字段较少的情况下;如果字段较多,扫描时间多,效率低;

项目中提倡使用某一个非 null 且唯一的字段,通常是主键。

SQL> select count(*) from emp;

  COUNT(*)
----------
        14
           

统计 emp 表中有多少个部门(去掉重复的):

SQL> select count(distinct deptno) from emp;

COUNT(DISTINCTDEPTNO)
---------------------
                    3
           

统计有佣金的员工人数:(不统计 NULL 的值)

SQL> select count(comm) from emp;

COUNT(COMM)
-----------
          4
           

2、sum():该函数用于求和;

求所有员工的总工资:

SQL> select sum(sal) "总工资" from emp;

    总工资
----------
     29025
           

3、avg():求平均值;

求员工的平均工资,四舍五入,保留小数点后 0 位:

SQL> select round(avg(sal),0) "平均工资" from emp;

  平均工资
----------
      2073
           

4、max():求最大值;

min():求最小值;

SQL> select max(sal) "最高工资",min(sal) "最低工资" from emp;

  最高工资   最低工资
---------- ----------
      5000        800
           

max() 和 min() 函数还可以用于日期:

SQL> select max(hiredate) "最晚入职时间",min(hiredate) "最早入职时间" from emp;

最晚入职时间   最早入职时间
-------------- --------------
23-5月 -87     17-12月-80
           

5、按部门求出该部门平均工资,且平均工资取整数,采用截断:

SQL> select deptno "部门编号",trunc(avg(sal),0) "部门平均工资"
  2  from emp
  3  group by deptno;

  部门编号 部门平均工资
---------- ------------
        30         1566
        20         2175
        10         2916
           

6、(继续)查询部门平均工资大于 2000 元的部门:

在分组的基础上再进行筛选,使用关键字 having;

SQL> select deptno "部门编号",trunc(avg(sal),0) "部门平均工资"
  2  from emp
  3  group by deptno
  4  having trunc(avg(sal),0) > 2000;

  部门编号 部门平均工资
---------- ------------
        20         2175
        10         2916
           

where 和 having 的区别:

1、where 是行过滤器,而 having 是组过滤器;

2、where 是针对原始的数据,而 having 是针对分组后的数据;

3、where 跟在 from 后面,而 having 跟在 group by 后面;

4、where 先执行,having 后执行;

7、(继续)按部门平均工资降序排列:根据列号(2)进行排序;

SQL> select deptno "部门编号",trunc(avg(sal),0) "部门平均工资"
  2  from emp
  3  group by deptno
  4  having trunc(avg(sal),0) > 2000
  5  order by 2 desc;

  部门编号 部门平均工资
---------- ------------
        10         2916
        20         2175
           

8、除10号部门外,查询部门平均工资大于 2000 元的部门,方式一【having deptno<>10】

SQL> select deptno,avg(sal)
  2  from emp
  3  group by deptno
  4  having deptno<>10;

DEPTNO   AVG(SAL)
------ ----------
    30 1566.66667
    20       2175
           

 9、除10号部门外,查询部门平均工资大于 2000元 的部门,方式二【where deptno<>10】

SQL> select deptno,avg(sal)
  2  from emp
  3  where deptno<>10
  4  group by deptno;

DEPTNO   AVG(SAL)
------ ----------
    30 1566.66667
    20       2175
           

方式一先分组,在分组之后再进行筛选;方式二先筛选,筛选之后再进行分组;

哪种方式好:

方式一的做法:假如 10 号部门有 500 个数据,好不容易把所有数据 按照部门分好组了,又要把 10 号部门去掉,那分组就白分了。而方式二的做法:先把 10 号部门的数据全部去掉,再把剩下的数据进行分组,效率要高。所以推荐方式二。

继续阅读