Oracle按照某个含有数字的字符串类型的字段进行排序时,将10排在9的后面

    xiaoxiao2022-06-26  157

    开发中遇到的一个排序问题,简单记录一下解决方式,供参考,如有更合适更好的解决方法,欢迎指正

     

    本文所写内容主要是针对想要排序的字段是同时符合以下情况的:

    1.VARCHAR2等字符串类型

    2.该字段的值非纯数字,类似于字母序号+数字序号的

    3.字符的长度不一致的,比如有些会用0来填充,保持长度一致,也是不需要文中这样处理的,例如:A001,A002这样子

     

    如果排序字段不符合上述情况:

    假如值是VARCHAR2型的纯数字,直接使用 order by to_number(字段名)即可;

    假如值的长度是一样的,直接order by 字段名也能按照正常的顺序排列。

     

    我自己造的一段数据,SQL如下:

    with tb as (   select 'A1' as 桌号,3 as 用餐人数,188 as 消费金额 from dual   union all   select 'A2' as 桌号,4 as 用餐人数,258 as 消费金额 from dual   union all   select 'A3' as 桌号,3 as 用餐人数,188 as 消费金额 from dual   union all   select 'A4' as 桌号,5 as 用餐人数,288 as 消费金额 from dual   union all   select 'A10' as 桌号,2 as 用餐人数,168 as 消费金额 from dual   union all   select 'A11' as 桌号,2 as 用餐人数,158 as 消费金额 from dual   union all   select 'B18' as 桌号,9 as 用餐人数,988 as 消费金额 from dual   union all   select 'B19' as 桌号,12 as 用餐人数,1188 as 消费金额 from dual   union all   select 'B20' as 桌号,11 as 用餐人数,1088 as 消费金额 from dual   union all   select 'A12' as 桌号,4 as 用餐人数,388 as 消费金额 from dual   union all   select 'A13' as 桌号,4 as 用餐人数,388 as 消费金额 from dual   union all   select 'A14' as 桌号,5 as 用餐人数,488 as 消费金额 from dual   union all   select 'A5' as 桌号,6 as 用餐人数,488 as 消费金额 from dual   union all   select 'A6' as 桌号,2 as 用餐人数,168 as 消费金额 from dual   union all   select 'A7' as 桌号,1 as 用餐人数,88 as 消费金额 from dual   union all   select 'A8' as 桌号,3 as 用餐人数,188 as 消费金额 from dual   union all   select 'A9' as 桌号,5 as 用餐人数,288 as 消费金额 from dual   union all   select 'A15' as 桌号,5 as 用餐人数,488 as 消费金额 from dual   union all   select 'B16' as 桌号,10 as 用餐人数,1488 as 消费金额 from dual   union all   select 'B17' as 桌号,15 as 用餐人数,2088 as 消费金额 from dual )

    select * from tb;

    直接查询出来的数据如下:

    然后想要按照 “桌号” 进行排序,如果直接使用order by进行排序的话,结果显示如下:

    select * from tb order by tb.桌号;

    可以很明显的看到A10排在了A1的后面,A2排到了A15的后面,非常不符合我们的期望,这时候我们就可以这样处理后再排序

    select * from tb order by length(tb.桌号),tb.桌号;

    查询结果如下:

     


    最新回复(0)