oracle高级语法

1.union和union all区别?

  1)查询数量而言

       union针对于重复的数据进行了过滤,只展示一条,起到了distinct的效果。而union all则展示全部。

 2)顺序而言

      union默认按第一列进行升序排列。而union all则按语句的先后顺序直接进行排序。

3)效率

     因为union all不需要去重并且排序,效率相对而言高一些。

eg:

--union all语句 合并
select * from emp where empno=7369
union all
select * from emp where empno=7499
union all
select * from emp where empno=7369
 

运行结果:

--union语句 合并去重并排序
select * from emp where empno=7369
union
select * from emp where empno=7499
union
select * from emp where empno=7369

运行结果:

 

2.intersect

   取的是两个结果的交集并且去重

select * from(
select * from emp where empno=7369
union all
select * from emp where empno=7499
union all
select * from emp where empno=7369
)
intersect
select * from(
select * from emp where empno=7369
union all
select * from emp where empno=7499
union all
select * from emp where empno=7369
)

运行结果:

3.minus  语法 A minus B

  A结果集存在但是B结果集不存在的数据,经过去重,按第一列进行升序后返回。

select * from(
select * from emp where empno=7369
union all
select * from emp where empno=7499
union all
select * from emp where empno=7369
)
minus
select * from emp where empno=7499

4.in和exists 都是用于返回匹配子句的结果集。oracle嵌套循环效率而言,保证外层循环数据量小于内存循环即可。

两者相互转换的前提,保证子查询返回的是非空数据。(null在oracle中表示未知。)

  in关键字,优先查询 子句,然后在跟主句进行依次匹配。

  exists关键字,优先查询 主句,而后在跟子句进行匹配操作。

select * from emp where empno in(
 select empno from emp where job='CLERK'
);
select * from emp e where exists (select 1 from emp where empno=e.empno and job='CLERK');

运行结果:

5.merge into

6.rollup 和 cube 都是求统计和。

  rollup是产生小计的和(rollup(a,b) -> (a,b)  (a) ()这三类分组计算聚合)

eg:

--按部门和工作进行分组,按部门分组,按空分组进行展示数据。
select min(sal),deptno,job from emp  group by  rollup(deptno,job)

运行结果:

--按部门工作分组 按部门分组 按空分组求和
select sum(sal),deptno,job from emp  group by  rollup(deptno,job)

运行结果:

cube是列联交叉表(cube(a,b,c)  abc,ab,ac,bc,a,b,c,null)

eg:

select sum(sal),deptno,job from emp  group by  cube(deptno,job)

运行结果:

**针对于空白处可以通过 grouping函数来增加汉字。如果存在值则返回0,否则返回1.

eg:

select decode(grouping(deptno),1,'按'||job||'统计',deptno),decode(grouping(job),1,'按'||deptno||'统计',job),sum(sal) from emp group by cube(deptno, job)

运行结果:

***针对于cube只想按展示部分规则的数据。则用 grouping sets ()进行选择展示。

eg:

select 
       sum(sal),deptno,job
  from emp
 group by grouping sets ((deptno,job),())

运行结果:

7.instr(sj,'-','-1') 查找字符串参数

sj:查询源,'-':查询的内容。‘-1’反向查询,大于0则正常查询匹配。最后还有个可选参数,默认返回第一个查询的接口,2则是查询满足条件的第二个。

要求截取-,取最后一个值。

with a as(

select '1-a' sj from dual

union

select '2-b-B' sj from dual

union

select '3' sj from dual

)

select substr(sj,instr(sj,'-','-1')+1,length(sj)) from a;

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值