Postgres自然顺序
Postgres natural order by
我在 postgres 中的一个列中有一个排序问题,该列具有诸如版本之类的值。
版本是字符变化的,具有如下值(未排序)。
1.2
1.3
1.10.1
1.9
如何按自然顺序排序,以便当我发出 SELECT version FROM TABLE_A ORDER BY version DESC
时它会给我
1.10.1
1.9
1.3
1.2
而不是
1.9
1.3
1.2
1.10.1
Postgres 允许您按数组排序——这实际上就是版本号所代表的。因此,您可以使用以下语法:
order by string_to_array(version, '.')::int[] desc
这是一个完整的例子:
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;
甚至 demonstration.
一种方式:(如果版本可能有最多 3 个部分则有效)
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
我在 postgres 中的一个列中有一个排序问题,该列具有诸如版本之类的值。 版本是字符变化的,具有如下值(未排序)。
1.2
1.3
1.10.1
1.9
如何按自然顺序排序,以便当我发出 SELECT version FROM TABLE_A ORDER BY version DESC
时它会给我
1.10.1
1.9
1.3
1.2
而不是
1.9
1.3
1.2
1.10.1
Postgres 允许您按数组排序——这实际上就是版本号所代表的。因此,您可以使用以下语法:
order by string_to_array(version, '.')::int[] desc
这是一个完整的例子:
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;
甚至 demonstration.
一种方式:(如果版本可能有最多 3 个部分则有效)
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