sql在oralce中降序排列字符串和数字组合

a1o7rhls  于 2021-08-13  发布在  Java
关注(0)|答案(1)|浏览(358)

我尝试将字符串和数字的组合按降序排序。
输入:

P9S1
P7S1
P13S1
P12S2
P10S1

预期产量:

P13S1
P12S2
P10S1
P9S1
P7S1

这是我试过的
示例代码:

with
      inputs (firmware) as (
        select 'P9S1'  from dual union all
        select 'P7S1' from dual union all
        select 'P13S1' from dual union all
        select 'P12S2' from dual union all
        select 'P10S1'      from dual
      )
    select firmware
    from   inputs
    order by 
    regexp_replace(firmware, '\d+\.\d+') desc ;

但这并不像预期的那样有效。任何帮助都将不胜感激。
谢谢

pcrecxhr

pcrecxhr1#

实际上,您没有解释字符串如何变成数字。
这适用于您的数据集:

order by to_number(regexp_replace(firmware, '\D', '')) desc

其思想是从字符串中删除所有非数字字符,将结果字符串转换为数字,并使用它进行排序。

with inputs (firmware) as (
    select 'P9S1' from dual union all
    select 'P7S1' from dual union all
    select 'P13S1' from dual union all
    select 'P12S2' from dual union all
    select 'P10S1' from dual
)
select firmware
from   inputs
order by to_number(regexp_replace(firmware, '\D', '')) desc ;
| FIRMWARE |
| :------- |
| P13S1    |
| P12S2    |
| P10S1    |
| P9S1     |
| P7S1     |

相关问题