Postgres natural order by

后端 未结 2 816
夕颜
夕颜 2021-01-15 15:52

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         


        
2条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-15 16:15

    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
    

提交回复
热议问题