我有這個 json 欄位,我想要結果作為日期。
select t.config_exit::json ->> 'earliest_exit' as Earliest_Exit
from table t
這給了我null或例如2021-11-03作為結果但作為文本欄位。
select t.config_exit::json ->> 'earliest_exit'::date as Earliest_Exit
from table t
我試過這個,但它不起作用。
uj5u.com熱心網友回復:
將json運算式放在括號之間,例如
SELECT (t.config_exit ->> 'earliest_exit')::date
FROM t;
演示: db<>fiddle
WITH t (config_exit) AS (
VALUES ('{"earliest_exit":"2021-11-03"}'::jsonb)
)
SELECT (t.config_exit ->> 'earliest_exit')::date
FROM t;
date
------------
2021-11-03
如果earliest_exit為空,它將失敗,因此您可能希望在投射之前將它們過濾掉。或者,您可以使用to_date,但它可能會給您不想要的日期:
WITH t (config_exit) AS (
VALUES ('{"earliest_exit":"2021-11-03"}'::jsonb),
('{"earliest_exit":""}'::jsonb),
('{"earliest_exit":null}'::jsonb)
)
SELECT to_date(t.config_exit ->> 'earliest_exit','YYYY-MM-DD')
FROM t;
to_date
---------------
2021-11-03
0001-01-01 BC
(3 Zeilen)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/348653.html
標籤:sql json PostgreSQL 铸件
