postgres 文本字段为具有空值和空值的数字
postgres text field to numeric with empty and null values
Postgres 10.8
我的数据库中有一个 JSON 字段,其中包含价格(如果有的话)。
我得到这样的值:
select t.config::jsonb ->> 'price' as price from mytable t
它以文本格式返回以下结果(null、空和价格):
[null],'',1330.0
我需要能够将此字段设为数字,以便稍后可以对该字段求和。
我试过这样解决:
select
(
case
when t.config::jsonb ->> 'price' is null then '0.00'
when t.config::jsonb ->> 'price' = '' then '0.00'
else t.config::jsonb ->> 'price'
end)::decimal as price
from mytable t
这给了我一个数字(131089,0)。我希望该字段类似于数字 (10,2)。必须有其他更简单的方法来做到这一点?
函数nullif
和coalesce
在这种情况下非常方便。 nullif(value,'')
returns null
如果值为空,coalesce(value,'0.00')
returns 0.00
如果值为 null
,所以你可能想要像这样链接两个函数:
SELECT
coalesce(nullif(t.config::jsonb ->> 'price',''),'0.00')::numeric(10,2) as price
FROM mytable t;
演示:db<>fiddle
Postgres 10.8
我的数据库中有一个 JSON 字段,其中包含价格(如果有的话)。
我得到这样的值:
select t.config::jsonb ->> 'price' as price from mytable t
它以文本格式返回以下结果(null、空和价格):
[null],'',1330.0
我需要能够将此字段设为数字,以便稍后可以对该字段求和。
我试过这样解决:
select
(
case
when t.config::jsonb ->> 'price' is null then '0.00'
when t.config::jsonb ->> 'price' = '' then '0.00'
else t.config::jsonb ->> 'price'
end)::decimal as price
from mytable t
这给了我一个数字(131089,0)。我希望该字段类似于数字 (10,2)。必须有其他更简单的方法来做到这一点?
函数nullif
和coalesce
在这种情况下非常方便。 nullif(value,'')
returns null
如果值为空,coalesce(value,'0.00')
returns 0.00
如果值为 null
,所以你可能想要像这样链接两个函数:
SELECT
coalesce(nullif(t.config::jsonb ->> 'price',''),'0.00')::numeric(10,2) as price
FROM mytable t;
演示:db<>fiddle