来自 JSON 的数据的 Postgres GROUP BY

Postgres GROUPBY on data coming from JSON

鉴于 table orders 包含两列:

| order_id | json |
| ---------| ---- |
| order_1 | {...} |
| order_2 | {...} |
| order_3 | {...} |

我想以 table 结束,每个订单一行,以及相关的购买商品总数,可以使用 json.

计算

Json结构(order_1的示例):

{
"id": order_1, 
"line_items": 
    [
    {"id": product_1, "quantity": 1}, 
    {"id": product_2, "quantity": 2}
    ]
}

期望输出:

| id | quantity |
| -- | -------- |
| order_1 | 3 |
| order_2 | 1 |
| order_3 | 2 |

这是到目前为止编写的代码:

SELECT 
order_id,
json_array_elements_text(raw_data::json#>'{line_items}')::json->>'quantity' as quantity_lines
FROM orders

输出以下内容 table:

| order_id | quantity_lines |
| -------- | -------------- |
| order_1 | 1 |
| order_1 | 2 |
| order_2 | 1 |
| order_3 | 1 |
| order_3 | 1 |

我错过了在 order_id 上聚合的最后一步。我试过传统的 GROUP BY:

SELECT 
order_id,
sum((json_array_elements_text(raw_data::json#>'{line_items}')::json->>'quantity')::int) as quantity_lines
FROM orders
GROUP BY order_id

但出现以下错误:

postgresql error: aggregate function calls cannot contain set-returning function calls

快接近了。让我们用 CTE 包装它。

with a as (SELECT
order_id,
json_array_elements_text(raw_data::json#>'{line_items}')::json->>'quantity' as quantity_lines
FROM orders)
select a.orderid, sum(quantity_lines) from a group by 1 order by 2;