【问题标题】:oracle PL/SQL: sort rowsoracle PL/SQL:对行进行排序
【发布时间】:2012-05-29 12:14:19
【问题描述】:

我使用 order by 运行查询,但我的列不是我想要的顺序

我想要这样:

产品

PROD_1
PROD_2
PROD_3
PROD_4
PROD_5
产品_6
PROD_7
PROD_8
PROD_9
PROD_10

但它给了我这个

产品

PROD_1
PROD_10
PROD_2
PROD_3
PROD_4
PROD_5
产品_6
PROD_7
PROD_8
PROD_9

【问题讨论】:

    标签: sql oracle sorting plsql


    【解决方案1】:

    您需要为每个位置添加一个 0,例如 01 用于数字 1-99 或 001 用于 1-999。或者,您必须拆分数值并在两个不同的列上进行排序。

    Ask Tom

    【讨论】:

    • +1 : @JamilSmith - 虽然用一列满足多种需求总是很诱人,但它也会产生额外的限制。通过同时拥有name 字段和sort order 字段,您可以使用任何您喜欢的名称和任何您喜欢的顺序。否则,名称会以您可能不希望的方式影响顺序。比如这个。 (但是,否则,PRODUCT_001 确实是仅使用名称字段来获取此信息的方法。)
    【解决方案2】:

    您正在尝试按字典顺序对实际上部分数字的内容进行排序。您可以在前面加上零(即 PROD_000001),但这很脆弱。在实际应用中,我假设 Prod 10 实际上在时间上晚于 Prod 1,因此您将按创建日期时间排序。

    【讨论】:

      【解决方案3】:
          SELECT to_number(substr(colname,INSTR(column_name,'_')+1))) prodno, column_name 
          from table_name
          order by prodno
      

      不是很优雅的解决方案,但这应该可以。 (因为我没有访问 Oracle 的权限,函数的参数可能需要调整。)这首先获取 _ 上的位置,使用它使用子字符串获取数字,然后将其转换为数字。如果表很大,您可能还需要查看性能

      【讨论】:

        【解决方案4】:

        您需要排序两次(注意我从 regexp_replace 更改为 regexp_substr 以允许返回 null 值)

        with
            a as (
            select 'PROD_1' product from dual union all 
            select 'PROD_10' product from dual union all 
            select 'PROD_2' product from dual union all 
            select 'PROD_3' product from dual union all 
            select 'PROD_4' product from dual union all 
            select 'PROD_5' product from dual union all 
            select 'PROD_6' product from dual union all 
            select 'PROD_7' product from dual union all 
            select 'PROD_8' product from dual union all 
            select 'PROD_9' product from dual union all 
            select 'DECEAD_1' product from dual union all 
            select 'DECEAD_10' product from dual union all 
            select 'DECEAD_2' product from dual union all 
            select 'DECEAD_20' product from dual union all 
            select 'TREE_FROG' product from dual 
            )
            select PRODUCT
                  , regexp_substr(product,'[^[:digit:]]*')  --return all non numeric
                  , regexp_substr(product,'[0-9]+') 
                  from a 
            order by regexp_substr(product,'[^[:digit:]]*')  ,
                     TO_NUMBER(regexp_substr(product,'[0-9]+')) --note explicit numeric cast
            ;
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-10-27
          • 1970-01-01
          • 2020-11-05
          • 2020-07-08
          • 1970-01-01
          • 2019-07-06
          • 1970-01-01
          • 2019-02-17
          相关资源
          最近更新 更多