2016-02-18 129 views
0

我們在表party_procedures如何在postgres中執行此查詢?

列數據看起來像這樣一個JSON列 'passed_states_data':

[{ 「狀態」: 「文件」, 「passed_at」:「2016年2月4日13:16:51 +0100「},{」state「:」problems「,」passed_at「:」2016-02-04 16:10:07 +0100「},{」state「:」waiting_for_physical_documents「,」 passed_at「:」2016-02-08 13:50:17 +0100「},{」state「:」customer_acceptance「,」passed_at「:」2016-02-08 13:50:19 +0100「} ,{「state」:「customer_identifier」,「passed_at」:「2016-02-08 13:50:54 +0100」},{「state」:「checking_account」,「passed_at」:「2016-02-08 13時51分45秒 0100 「},{」 狀態 「:」 transfer_money_to_savings_account」, 「passed_at」: 「2016年2月10日9點12分18秒 0100」}]

我需要構建僅返回存在'transfer_money_to_savings_account'的行的查詢,然後獲取passed_at日期。

所以查詢應該返回是這樣的:

select blah as "date passed" from party_procedures pp 
    where json_array_elements(pp.passed_states_data)->>'state'='transfer_money_to_savings_account' = 't' 

或類似的東西。

回答

0

json_array_elements()函數返回設置json,因此,您不能使用->>;換句話說,您需要遍歷json數組元素的集合,並檢查state是否有您需要查找的值。

WITH t(passed_states_data) AS (VALUES 
    ('[{"state":"documents","passed_at":"2016-02-04 13:16:51 +0100"}, 
    {"state":"problems","passed_at":"2016-02-04 16:10:07 +0100"}, 
    {"state":"waiting_for_physical_documents","passed_at":"2016-02-08 13:50:17 +0100"}, 
    {"state":"customer_acceptance","passed_at":"2016-02-08 13:50:19 +0100"}, 
    {"state":"customer_identifier","passed_at":"2016-02-08 13:50:54 +0100"}, 
    {"state":"checking_account","passed_at":"2016-02-08 13:51:45 +0100"}, 
    {"state":"transfer_money_to_savings_account","passed_at":"2016-02-10 09:12:18 +0100"}]'::JSON) 
) 
SELECT j->>'passed_at' as "date passed" FROM t, json_array_elements(t.passed_states_data) j 
WHERE j->>'state' = 'transfer_money_to_savings_account'; 

結果:

 date passed   
--------------------------- 
2016-02-10 09:12:18 +0100 
(1 row)