oracle层次查询数据重复,[数据库]Oracle层次查询

本文介绍了如何使用Oracle的层次查询来解决字符串拆分问题,提供了三种不同的解法,包括利用REPLACE函数、正则表达式和非层次查询。此外,还展示了在Oracle 10g中使用层次查询实现类似11g中LISTAGG函数的效果。
摘要由CSDN通过智能技术生成

[数据库]Oracle层次查询

0 2015-08-07 11:00:10

1. 根据时间先后顺序,十二星座的英文名称用逗号串起来为'Aries,Taurus,Gemini,Cancer,Leo,Virgo,Libra,Scorpio,Sagittarius,Capricorn,Aquarius,Pisces',请用带层次查询的sql替换下面的sql中的[...]部分,使该sql能将字符串拆分为12条记录。

with t as (select 'Aries,Taurus,Gemini,Cancer,Leo,Virgo,Libra,Scorpio,Sagittarius,Capricorn,Aquarius,Pisces' str from dual)

[...]

其实,该题有几种不同的解法。

解法1:利用replace函数with t as (select 'Aries,Taurus,Gemini,Cancer,Leo,Virgo,Libra,Scorpio,Sagittarius,Capricorn,Aquarius,Pisces' str from dual)select replace(str,',',chr(10)) constellation from t

但是这种解法有点瑕疵,题目要求输出12条记录,该解法虽然呈现的是12行,但实际只是一行记录。

解法2:利用层次查询with t as (select 'Aries,Taurus,Gemini,Cancer,Leo,Virgo,Libra,Scorpio,Sagittarius,Capricorn,Aquarius,Pisces' str from dual)select regexp_substr(str,'\w{1,}',1,rownum) constellation from t,dual connect by rownum<=12

这里同时也用到了正则表达式

解法3:非层次查询with t as (select 'Aries,Taurus,Gemini,Cancer,Leo,Virgo,Libra,Scorpio,Sagittarius,Capricorn,Aquarius,Pisces' str from dual),t1 as (select instr(str||',',',',1,rownum)pos from t,dual connect by rownum<=12),t2 as (select pos,lag(pos,1,0)over(order by pos) prev from t1)select substr(str,prev+1,pos-prev-1) constellation from t,t2

这种解法花费了较多时间才想出。

2. 已知在11g下,下面sql

select deptno, cast(listagg(ename,',')within group(order by empno) as varchar2(50)) nl from emp group by deptno order by deptno;

的运行结果为:

DEPTNO NL

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

10 CLARK,KING,MILLER

20 SMITH,JONES,SCOTT,ADAMS,FORD

30 ALLEN,WARD,MARTIN,BLAKE,TURNER,JAMES

请用层次查询写出在10g下可以达到得到同样结果的sqlwith t as (select deptno,ename,lag(ename)over(partition by deptno order by ename)lag_name from emp),t1 as (select deptno,max(sys_connect_by_path(ename,',')) name from t start with lag_name is null connect by prior ename=lag_name group by deptno)select deptno,cast(regexp_replace(name,',','',1,1) as varchar2(40))nl from t1 order by 1;

转载请保留本文网址:http://www.shaoqun.com/a/131467.html

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们:admin@shaoqun.com。

oracle

0

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值