2017-03-02 97 views
0

我想執行我的表到JSONB字段的具體查詢,但無法獲得最終輸出爲int。 假設每行都是以下格式的JSONB字段,我想要獲得每個產品的訂單總數。在JSONB字段彙總值

{ 
    "Product A": { 
     "orders": {"total": 2, "stuff": 3} 
     "..." 
    }, 
    { 
    "Product B": { 
     "orders": {"total": 1, "stuff": 1} 
     "..." 
    }, 
    { 
    "Product C": { 
     "orders": {"total": 5, "stuff": 0} 
     "..." 
    } 
} 

我已經做了查詢:

select key as product, value::json->'orders'->'total' as total 
from table, jsonb_each_text(json_field) 
group by key, value; 

有了這個,我能夠通過產品獲得總:

product  | total 
Product A | 10 
Product B | 15 
Product C | 0 

但是似乎總是jsonb場,我試着使用(value :: json - >'orders' - >'total'):: numeric,但是它表示該轉換是不可能的。你能幫忙嗎?

+1

你應該使用'jsonb_each(json_field)'和'價值 - > '秩序' - >>「total''。您可以將其轉換爲數字(但只有當該字段實際上是一個JSON號碼時,無處不在)。 – pozs

+0

很酷。謝謝。 – absg

回答

0

我終於能夠做到這一點:

所需轉換轉換爲數字像以前一樣的文字:

(value::json->'orders'->'total')::text::numeric 
+0

或者只是:'(value :: json - >'orders' - >>'total'):: numeric' –