【问题标题】:postgres text field to numeric with empty and null valuespostgres 文本字段到具有空值和空值的数字
【发布时间】:2021-12-18 12:02:31
【问题描述】:

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)。一定有其他更简单的方法可以做到这一点吗?

【问题讨论】:

    标签: sql json postgresql casting


    【解决方案1】:

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

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

    演示:db<>fiddle

    【讨论】:

    • 是的,它给了我相同的输出,但代码少得多,谢谢!不过,我仍然想知道一件事。在 dbeaver 中,当我将鼠标悬停在表中的其他数字字段上时,它会显示数字(10,2),但如果我将鼠标悬停在这个数字字段上,它会显示数字(131089,0)???
    • @user2210516 你看到我最后的编辑了吗? SELECT coalesce(nullif(t.config::jsonb ->> 'price',''),'0.00')::numeric(10,2) as price FROM mytable t;
    猜你喜欢
    • 2021-09-11
    • 2011-11-23
    • 1970-01-01
    • 1970-01-01
    • 2021-09-02
    • 1970-01-01
    • 1970-01-01
    • 2018-11-14
    • 1970-01-01
    相关资源
    最近更新 更多