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)。必須有其他更簡單的方法來做到這一點?
uj5u.com熱心網友回復:
在這種情況下,功能nullif和coalesce可以非常方便。nullif(value,'')回報null的情況下,為空值和coalesce(value,'0.00')收益0.00的情況下,價值null,所以你想可能鏈中的功能是這樣的:
SELECT
coalesce(nullif(t.config::jsonb ->> 'price',''),'0.00')::numeric(10,2) as price
FROM mytable t;
演示: db<>fiddle
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/348643.html
標籤:sql json PostgreSQL 铸件
上一篇:為專案生成帶有測驗資料的多行
