我有以下PostgreSQL表:
CREATE TABLE orders
(
id uuid NOT NULL,
order_date timestamp without time zone,
data jsonb
);
其中数据包含这样的json文档:
{
"screws": [
{
"qty": 1000,
"value": "Wood screw"
},
{
"qty": 500,
"value": "Drywall screw"
},
{
"qty": 500,
"value": Concrete screw"
}
],
"nails": [
{
"qty": 1000,
"value": "Round Nails"
}
]
}
如何获得所有订单中所有类型螺钉的总量?像这样的东西:)
select value, sum(qty) from orders where section = 'screws' group by value;
答案 0 :(得分:1)
我不太确定您为什么要对qty
值求和,因为GROUP BY value
仅在相同的value
可以求和的几倍时才有意义,例如如果您的值Wood screw
为两倍。
不过,这将是查询:
SELECT
elems ->> 'value' AS value,
SUM((elems ->> 'qty')::int) AS qty
FROM
orders,
jsonb_array_elements(data -> 'screws') elems
GROUP BY 1
jsonb_array_elements()
将丝杠数组扩展为每个数组元素一行。->>
运算符(给出text
类型)获取数量值,并将其转换为int
类型