2017-03-02 106 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' –