【问题标题】:How to order query by number first and then by string in the same field如何在同一字段中先按数字排序查询,然后按字符串排序
【发布时间】:2013-07-27 19:00:18
【问题描述】:

我在 PostgreSQL 9.0 中有一个数据库,它有一个带有字符串字段的表来存储客户端代码。 这些代码是字母数字的,可以以字母或数字开头,例如1, 2, A0001-4, A0001-2, 10

我想先按数字排序,然后按字符串排序,比如

1, 2, 10, A0001-2, A0001-4

我使用to_number(fields, '99999999') 执行此操作,例如:

SELECT * FROM empleados ORDER BY to_number(legajo, '99999999'), legajo

但是当代码像've',没有数字时,查询失败。

我能做什么?

【问题讨论】:

    标签: sql postgresql pattern-matching sql-order-by natural-sort


    【解决方案1】:

    您可以使用 case 语句来查找数字:

    select *
    from empleados
    order by (case when legajo not similar to '%[^0-9]%' then 1 else 0 end) desc,
             (case when legajo not similar to '%[^0-9]%' then to_number(legajo, '999999999') end),
             legjo;
    

    similar to 表达式表示所有字符都是数字。

    编辑:

    修复了语法错误。你可以测试一下:

    with empleados as (
          select 'abc' as legajo union all
          select '123'
         ) 
    select *
    from empleados
    order by (case when legajo not similar to '%[^0-9]%' then 1 else 0 end) desc,
             (case when legajo not similar to '%[^0-9]%' then to_number(legajo, '999999999') end),
             legajo;
    

    SQLFiddle 是 here

    【讨论】:

      【解决方案2】:
      WITH empleados(legajo) AS (
         VALUES
           ('A0001-4'::text)
          ,('123.345-56')
          ,('ve')
          ,('123')
          ,('123 ve')
         ) 
      SELECT *
      FROM   empleados
      ORDER  BY CASE WHEN legajo ~ '\D' THEN 1000000000::int
                                        ELSE to_number(legajo, '999999999')::int END
            ,legajo;
      

      ~ is the regular expression operaor.
      \D is the classs shorthand for non-digits.

      legajo (legajo ~ '\D') 中包含非数字字符的行稍后出现。

      -> SQLfiddle demo

      Never use SIMILAR TO,这是一个完全没有意义的运营商。

      【讨论】:

        【解决方案3】:

        试试这个:

        select *
        from empleados
        order by
            case
                when legajo similar to '%[0-9]%' then to_number(legajo, '999999999')
                else 999999999
            end,
            legajo
        

        sql fiddle demo

        【讨论】:

          猜你喜欢
          • 2013-06-29
          • 1970-01-01
          • 1970-01-01
          • 2021-11-28
          • 2021-09-13
          • 2021-12-20
          • 1970-01-01
          • 2018-03-11
          • 1970-01-01
          相关资源
          最近更新 更多