Postgresql ORDER BY空格

时间:2013-11-08 10:08:00

标签: sql ruby-on-rails postgresql

假设我有一个包含一列的表格,即:

5 absolute
5.0
5.1
last
50
5 elite
edge

我需要订购它(使用postgresql方法):

5 absolute
5 elite
5.0
5.1
50
edge
last

但如果我使用经典的“ORDER BY column ASC”,我会得到:

50
5.0
5.1
5 absolute
5 elite
edge
last

有许多工具,比如substring或using,但我无法理解它们是如何工作的。

我需要做什么?

2 个答案:

答案 0 :(得分:1)

不知道,可能是这样的:

with cte as (
   select col1, regexp_split_to_array(col1, ' ') as d
   from Table1

)
select col1
from cte
order by
    d[1] ~ '^([0-9]+[.]?[0-9]*|[.][0-9]+)$' desc,
    case
        when d[1] ~ '^([0-9]+[.]?[0-9]*|[.][0-9]+)$' then
            d[1]::numeric
    end,
    d[2]

<强> sql fiddle demo

这个将字符串按空格分割为数组,将第一个条目转换为数字,并按此数字和剩余字符串对结果进行排序

答案 1 :(得分:0)

这应该这样做:

order by regexp_replace(the_column, '[^0-9\.]', '', 'g')::numeric DESC

它从值中删除所有非数字字符(仅保留数字和.),然后将其转换为数字。然后使用该数字对降序进行排序

唯一的一点就是5.0将在5.1之后按上述方式排序。

如果您需要考虑没有任何数字的值,请执行以下操作:

order by 
      case 
         when regexp_replace(the_column, '[^0-9\.]', '', 'g') <> 
            then regexp_replace(the_column, '[^0-9\.]', '', 'g')::numeric
      end DESC NULLS LAST, 
      the_column DESC -- to sort the "NULL" values alphabetically

如果您不想重复正则表达式,可以执行以下操作:

with clean_data as (
   select the_column, 
          regexp_replace(the_column, '[^0-9\.]', '', 'g') as clean_column, 
          ....
   from ...
)
select *
from clean_data
order by case 
           when clean_column <> '' then clean_column::numeric 
         end desc nulls last, 
         the_column desc;