【问题标题】:How to sort this table by descending integer value?如何按整数值降序对该表进行排序?
【发布时间】:2017-01-19 04:31:14
【问题描述】:

表定义是这样的:

create table test_1
( match_id varchar2(30), ts timestamp );

match_id 为整数格式。[A|B],如 1.A、1.B、99.A 或 99.B。 match_id 在同一整数上的行称为一对,因此 1.A 和 1.B 是一对,而 99.A 和 99.B 是另一对。数据库是 Oracle 11.2 或更高版本。

SQL> insert into test_1 values ('1.A',current_timestamp);
SQL> insert into test_1 values ('1.B',current_timestamp-10);
SQL> insert into test_1 values ('100.A',current_timestamp-20);
SQL> insert into test_1 values ('100.B',current_timestamp-30);
SQL> insert into test_1 values ('99.A',current_timestamp-40);
SQL> insert into test_1 values ('99.B',current_timestamp-50);

我想按 match_id 列中整数值的降序选择此表,例如 100.B、100.A、99.B、99.A、1.B、1.A 但以下语句返回 99 .B、99.A、100.B、100.A、1.B、1.A。请提出建议。

SQL> select * from test_1 order by match_id desc;

【问题讨论】:

    标签: sql oracle


    【解决方案1】:

    试试;

    Select  * 
    from test_1
    order by TO_NUMBER(SUBSTR(match_id, 1, LENGTH(match_id) - 2)) desc;
    

    这里假设除了最后两个字符,其他字符都是有效数字。

    或使用REGEXP_SUBSTR

    Select  * 
    from test_1
    order by TO_NUMBER(REGEXP_SUBSTR(match_id,'^[0-9]+')) desc
    

    这将只取开头的数字

    【讨论】:

      【解决方案2】:

      这是一个更简单的想法,如果您对输入字符串的长度(字符数)有一个限制,您无需检查数据就知道。

      ...order by lpad(match_id, 20, '0') desc    --  assuming all the strings are length <= 20
      

      即:将所有内容都视为字符串。如果需要,通过在左侧添加零使它们的长度相同。然后按字母顺序排序(包括句点和字母 A 或 B)与排序数字部分然后是 A 和 B 相同 - 所有这些都是降序的。 (请注意,仅按数字部分排序并不能保证 B 会在 A 之前!)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多