how to use order by in alphanumeric column in oracle

只愿长相守 提交于 2019-12-23 12:26:15

问题


In my table one of column i have a value like below

Y-1
Y-2
Y-3
Y-4
Y-5
Y-6
Y-7
Y-8
Y-9
Y-10
Y-11
Y-12
Y-13
Y-14

when i am order by this column its working fine if the row has value up to Y-9 other wise my result is wrong like below.

Y-1
Y-10
Y-11
Y-12
Y-13
Y-14
Y-2
Y-3
Y-4
Y-5
Y-6
Y-7
Y-8
Y-9

But i want the output like below

Y-1
Y-2
Y-3
Y-4
Y-5
Y-6
Y-7
Y-8
Y-9
Y-10
Y-11
Y-12
Y-13
Y-14

How to acheive the above result.i am using oracle database.Any help will be greatly appreciated!!!!!


回答1:


You can use an order by manipulatinng the column content and cast to number eg:

 order by substr(col1, 1,2), TO_NUMBER(sustr(col1, 3,10))



回答2:


Assuming the data is in a table t with a column col and the structure is an alphabetical string followed by dash followed by a number, and both the alphabetical and the number are always not NULL, then:

select col from t
order by substr(col, 1, instr(col, '-')), to_number(substr(col, instr(col, '-')+1))



回答3:


I think the good way is to get constant length field

select col from t
order by substr(col, 1, 2)|| lpad(substr(col, 3),5,'0')

it will correct work only with two nondigit simbol in begining of string up to 99999 number



来源:https://stackoverflow.com/questions/40342049/how-to-use-order-by-in-alphanumeric-column-in-oracle

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