![](/img/trans.png)
[英]How to convert text field to numeric field and null non-numeric values?
[英]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)。 必须有其他更简单的方法来做到这一点?
在这种情况下,函数nullif
和coalesce
会非常方便。 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.