oracle基础知识2

1,通用函数

a,-------------------------------------------------------------
nvl(exp1,exp2)//若exp1 为null,则返回exp2的值,否则返回exp1的值
eg: select ename,sal,comm,sal+nvl(comm,0) from emp;  //null+值为null;
select ename,hiredate,nvl(hiredate,sysdate) from emp;
select ename,job,nvl(job,'not job yet') from emp;
select ename,hiredate,to_char(nvl(hiredate,sysdate),'yyyy-mm-dd day') from emp;
insert into emp(empno,ename,job) values(8888,'张三','ChairMan');
b,-------------------------------------------------------------------------
nvl2(exp1,exp2,exp3)若exp1的值不为null,返回exp2,否则返回exp3的值
eg: select ename,sal,comm,nvl2(comm,sal+comm,sal) total from emp;//total为别名
nullif(exp1,exp2)若exp1与exp2的值相等则返回null,否则返回exp1的值
eg: select name 原名,nullif(pen_name,name) 化名 from author;
coalesce(exp1,exp2......)//依次考察各参数表达式,遇到非null值即停止并返回。
select ename,sal,comm,coalesce(sal+comm,sal,0)总收入 from emp;
c,-----------------------------------------------------------------------
case表达式
case exp when comparison_exp1 then return_exp1
        [ when comparison_exp2 then return_exp2
         when comparison_exp3 then return_exp3
         when comparison_expn then return_expn
         else else_exp]
end
eg:   select empno,ename,sal,
           case deptno+10 when 10 then '财务部'
                       when 20 then '研发部'
                       when 30 then '销售部'
                       else '未知部门'
           end 部门
      from emp;    //部门是别名

decode() 函数
decode(col|expression,search1,result1
                     [search2,result2......]
                     [default])

select empno,ename,sal,
       decode(deptno,10,'财务部',
                     20,'研发部',
                     30,'销售部',
                     '未知部门')
       部门
from emp;
--------------------------------------------------------------------
单行函数可以嵌套使用,嵌套层次无限制
嵌套函数的执行顺序是由内到外
select empno,lpad(initcap(trim(ename)),10,'') name,job,sal from emp;  
---------------------------------------------------------------------
分组函数对一组数据进行运算,针对一组数据(多行记录)只返回一个结果,也称多行函数
常用分组函数
avg(),count(),max(),min(),sum()
eg: select avg(sal),max(sal),min(sal),sum(sal) from emp;
select max(hiredate),min(hiredate) from emp;
count(*)返回组中总记录数目
count(exp)返回表达式exp值非空的记录数目
count(distinct(deptno)) from emp;返回表达式不重复,非空的记录数目
select count(*) from emp;
select count(comm) from emp;
select count(distinct(deptno)) from emp;
分组函数省略列中的空值。空值不算。
select avg(comm) from emp;相当与sum(nvl(comm,0))/count(comm);
注意与sum(nvl(comm,0))/count(*);

select deptno,avg(sal),count(*)记录数 from emp
where sal>1200
group by deptno
order by avg(sal);//where-----group by-------order by

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

select deptno,avg(sal)
from emp
where avg(sal)>2000;   //不允许在where子句子中使用分组函数,还没分组
group by deptno;

select deptno,job,avg(sal)
from emp
where hiredate>=to_date('1981-05-01','yyyy-mm-dd')
group by deptno,job
having avg(sal)>120
order by deptno,job;
 

你可能感兴趣的:(oracle基础知识2)