我有两列,id integer
and version text
。我正在尝试将字符串转换为version
转换为整数,以便我可以选择 id 的最大(最新)版本。
然而,第一个实例id
将自身存储为version
。例子:
id | version
---+--------
10 | '10'
与以下相反:
id | version
---+--------
10 | '10-0'
附加行遵循约定 id:10,版本:10-1。 ETC。
我怎样才能做到这一点?我努力了split_part()
并投射为int
。然而,split_part(version, "-", 2)
将返回看起来像空字符串的内容。我尝试过使用COALESCE(splitpart..., '0')
无济于事,因为它尝试读取字段索引 2 返回的空字段。
使用组合合并()和nullif(), https://www.postgresql.org/docs/current/static/functions-conditional.html#FUNCTIONS-COALESCE-NVL-IFNULL例子:
with my_table(version) as (
values
('10'), ('10-1'), ('10-2')
)
select
version,
split_part(version, '-', 1)::int as major,
coalesce(nullif(split_part(version, '-', 2), ''), '0')::int as minor
from my_table
version | major | minor
---------+-------+-------
10 | 10 | 0
10-1 | 10 | 1
10-2 | 10 | 2
(3 rows)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)