Postgres natural order by

匆匆过客 提交于 2019-12-01 09:30:24

问题


I have a sorting issue in postgres in a column with values such as version. Version is character varying, with values such as the following (un-ordered).

1.2
1.3
1.10.1
1.9

How do I sort in natural order such that when I issue SELECT version FROM TABLE_A ORDER BY version DESC it will give me

1.10.1
1.9
1.3
1.2

instead of

1.9
1.3
1.2
1.10.1

回答1:


Postgres allow you to sort by arrays -- which is essentially what the version number represents. Hence, you can use this syntax:

order by string_to_array(version, '.')::int[] desc

Here is a full example:

select *
from (values ('1'), ('2.1'), ('1.2.3'), ('1.10.6'), ('1.9.4')) v(version)
order by string_to_array(version, '.')::int[] desc;

And even a demonstration.




回答2:


One way: (works if version may have maximum 3 parts)

with t(col) as(
    select '1.9' union all
    select '2' union all
    select '1.2' union all
    select '1.10.1'  
)
select * from t
order by 
case when split_part(col, '.', 1) = '' then 0 else split_part(col, '.', 1)::int end desc, 
case when split_part(col, '.', 2) = '' then 0 else split_part(col, '.', 2)::int end desc, 
case when split_part(col, '.', 3) = '' then 0 else split_part(col, '.', 3)::int end desc


来源:https://stackoverflow.com/questions/43897440/postgres-natural-order-by

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!