ORACLE 多字段排序再合并

本文讨论了Oracle数据库在10G和11G版本中处理多字段排序的不同之处,通过一个具体的示例展示了10G环境下需要如何调整SQL语句以获得与11G相同的结果。内容涉及ID和END字段的排序,以及如何合并排序后的数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

drop table temp ;

create table temp ( id number , st varchar2(100), end varchar2(100)) ;

insert into temp values( 1 , 11,null) ;
insert into temp values( 1 , 66,null) ;
insert into temp values( 1 , 33,null) ;
insert into temp values( 1 , null,22) ;
insert into temp values( 1 , null,55) ;
insert into temp values( 2 , 33,null) ;
insert into temp values( 2 , 77,null) ;
insert into temp values( 2 , 11,null) ;
insert into temp values( 2 , null,22) ;
insert into temp values( 2 , null,55) ;
insert into temp values( 2 , null,99) ;
commit;

select * from temp ; 


select t2.id
,regexp_replace(regexp_replace(ltrim(max(sys_connect_by_path(st,',')),','),'[,]{2,}',','),',$','')
,regexp_replace(regexp_replace(ltrim(max(sys_connect_by_path(end,',')),','),'[,]{2,}',','),',$','')
from  (
select t1.*, lead(le1) over(partition by id  order by le1 desc) le2 from 
( select T.*, ROW_NUMBER() OVER( order by st||end) le1 from TEMP T ) t1 ) t2
start with le2 is null
connect by  le2 = prior le1
group by id 


源表数据:

select * from temp ;

    ID ST END
1 1 11
2 1 66
3 1 33
4 1 22
5 1 55
6 2 33
7 2 77
8 2 11
9 2 22
10 2 55
11 2 99


执行结果:

1 1 11,33,66 22,55
2 2 11,33,7722,55,99


上述SQL 在 11G中运行没问题, 在10G环境需改为:


with temp_data as (
select t1.*, lead(le1) over(partition by id  order by le1 desc) le2 from   
 ( select T.*, ROW_NUMBER() OVER( order by st||end) le1 from TEMP T ) t1 
 ) 
select t2.id  
,regexp_replace(regexp_replace(ltrim(max(sys_connect_by_path(st,',')),','),'[,]{2,}',','),',$','')  
,regexp_replace(regexp_replace(ltrim(max(sys_connect_by_path(end,',')),','),'[,]{2,}',','),',$','')  
from  temp_data t2  
start with le2 is null  
connect by  le2 = prior le1  
group by id   


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值