繁体   English   中英

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],'',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)。 必须有其他更简单的方法来做到这一点?

在这种情况下,函数nullifcoalesce会非常方便。 nullif(value,'')在 value 为空的情况下返回null并且coalesce(value,'0.00')在 value 为null情况下返回0.00 ,因此您可能希望像这样链接两个函数:

SELECT 
 coalesce(nullif(t.config::jsonb ->> 'price',''),'0.00')::numeric(10,2) as price 
FROM mytable t;

演示: db<>fiddle

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM