sorting alpanumeric strings in Oracle 11g

最后都变了- 提交于 2019-12-12 06:15:39

问题


I have a client that needs a report on Lawson tokens sorted in a strict alphanumeric order. The following is a sample test file and the query I have been using without success. I am not sure why the regex_replace is not working well here. I will appreciate any help I can get.

Thanks.

enter code here

create table sortest (token varchar2(6));

insert into sortest values ("BR00.1');
insert into sortest values ("BRFL.1');
insert into sortest values ("BRBF.1');
insert into sortest values ("BR00.2');
insert into sortest values ("BRRF.1');
insert into sortest values ("BRIP.1');
insert into sortest values ("BRRF.3');
insert into sortest values ("BR00.3');
insert into sortest values ("BRBF.2'); 
insert into sortest values ("BRRF.2');
insert into sortest values ("BR01.2');
insert into sortest values ("BR06.1');
insert into sortest values ("BR01.1');
insert into sortest values ("BR17.1');
insert into sortest values ("BR132');
insert into sortest values ("BR120');
insert into sortest values ("BR12.1');
insert into sortest values ("BR121');
insert into sortest values ("BR13.2');

commit;

select * from sortest
--order by token
order by to_number(nvl(trim(regexp_replace(token,'[A-Za-z]')),0)) asc
;

This returns '.....BR06.1, BR12.1, BR120, BR121, BR13.2, BR132, BR17.1....' etc. The order should put BR13.2 and BR17.1 before BR120 and BR121 for instance.


回答1:


What you've shown in the question orders just by the numeric part of the value, so you'll see something like:

TOKEN
------
BRIP.1
BRFL.1
BRBF.1
BR00.1
BRRF.1
BR00.2
BRRF.2
BRBF.2
BR00.3
BRRF.3
BR01.1
BR01.2
BR06.1
BR12.1
BR13.2
BR17.1
BR120 
BR121 
BR132 

If you want to order by the alphabetic characters and then by the numbers within those, you could use two expressions in the order by clause - so you order by the first alphabetic section, and then by the number formed from what's left after all alphabetic characters are stripped out:

select * from sortest
order by regexp_substr(token, '[[:alpha:]]*'),
  to_number(regexp_replace(token, '[[:alpha:]]', null));

TOKEN
------
BR00.1
BR00.2
BR00.3
BR01.1
BR01.2
BR06.1
BR12.1
BR13.2
BR17.1
BR120 
BR121 
BR132 
BRBF.1
BRBF.2
BRFL.1
BRIP.1
BRRF.1
BRRF.2
BRRF.3


来源:https://stackoverflow.com/questions/29751630/sorting-alpanumeric-strings-in-oracle-11g

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!