如何在 Oracle 中获得自然数字排序顺序?

How can I get a natural numeric sort order in Oracle?

我有一列字母后跟数字或字母:

ID_Col
------
S001
S1001
S090
SV911
SV800
Sfoofo
Szap
Sbart

我怎样才能自然地用 数字先 (ASC) 然后按字母顺序排序?如果以S开头,其余字符为数字,则按数字排序。否则,按字母排序。所以 SV911 应该排在字母的末尾,因为它还包含一个 V。例如

ID_Col
------
S001
S090
S1001
Sbart
Sfoofo
SV800
SV911
Szap

我看到这个 solution 使用正则表达式结合 TO_NUMBER 函数,但是因为我也有没有数字的条目,所以这对我来说似乎不起作用。我试过表达式:

ORDER BY 
    TO_NUMBER(REGEXP_SUBSTR(ID_Col, '^S\d+$')), 
    ID_Col 

    /* gives ORA-01722: invalid number */

这会有帮助吗?

SQL> with test (col) as
  2  (select 'S001'   from dual union all
  3   select 'S1001'  from dual union all
  4   select 'S090'   from dual union all
  5   select 'SV911'  from dual union all
  6   select 'SV800'  from dual union all
  7   select 'Sfoofo' from dual union all
  8   select 'Szap'   from dual union all
  9   select 'Sbart'  from dual
 10  )
 11  select col
 12  from test
 13  order by substr(col, 1, 1),
 14    case when regexp_like(col, '^[[:alpha:]]\d') then to_number(regexp_substr(col, '\d+$')) end,
 15    substr(col, 2);

COL
------
S001
S090
S1001
Sbart
Sfoofo
SV800
SV911
Szap

8 rows selected.

SQL>