wKiom1hlEO-SguzsAABh8bZO-Vc586.png-wh_50

函数的分类

单行函数:一个input对应一个output,input和output存在一一对应的关系 如lower

组函数:多个input,但是只对应一个output。如 sum()

------------------------------------------------------------------------------------


1、组函数(多行函数)默认情况下组函数   

     SQL>select min(sal),max(sal),sum(sal),avg(sal) from emp where empno=10;  


2、max min :统计日期数字和字符串

     SQL>select min(hiredate),max(hiredate) from emp;  

     SQL>select min(ename),max(ename) from emp;


3、count:用于结果集进行一个计数

①count(*):统计结果集为空的行

     SQL>select count(*) from emp;  

②count(xxx):不统计结果集为空的行(只统计满足表达式的非空行)

     SQL>select count(comm) from emp where deptno=30; 

     SQL>select count(comm) from emp;  

③count(distinct xxx):distinct-剔除重复的行

     SQL>select count(distinct deptno) from emp;


4、avg(xxx)求平均值

     SQL>select avg(sal) from emp;

     SQL>select avg(comm) from emp;  

     SQL>select avg(nvl(comm,0)) from emp; 统计所有人的平均奖金



5、group by:分组

①单列分组

     SQL>select avg(sal) from emp group by deptno;

     结果集没意义:需要在前面加上列名 

     SQL>select deptno,avg(sal) from emp group by deptno;

     SQL>select deptno,ename,avg(sal) from emp group by deptno;


②多列分组

先对部门分组,在对相同部门下的相同工作进行分组,在求平均值?

     SQL>select deptno,job,avg(sal) from emp group by deptno,job;

错误示例:

     SQL>select deptno,avg(sal) from emp;    


6、having:过滤

①分组之后还是想进行过滤,想要求出部门平均工资大于xxx的

     SQL>select deptno,avg(sal) from emp group by deptno;


    DEPTNO   AVG(SAL)

---------- ----------

        30 1566.66667

        20       2175

        10 2916.66667


7、条件表达式

①case

select ename,job,

  case

        when deptno=10 then sal

        when deptno=20 then 2*sal

        when deptno=30 then 3*sal

        else sal/2

  end new_sal

from emp;


②decode

select ename,job,decode(deptno,20,2*sal) from emp;

select ename,job,decode(deptno,20,2*sal,sal) from emp;

select ename,job,decode(deptno,10,sal,20,2*sal,30,3*sal,sal/2) from emp;


③只显示10号部门的工资,不是10号部门的用0表示

     SQL>select case when deptno=10 then sal else 0 endfrom emp;

     SQL>select deptno,avg(sal) from emp group by deptno having avg(sal)>2000;