給定orders包含兩列的表:
| order_id | json |
| ---------| ---- |
| order_1 | {...} |
| order_2 | {...} |
| order_3 | {...} |
我想最終得到一個表格,每個訂單都有一行,以及相關的購買物品總數,可以使用 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
輸出下表:
| 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
uj5u.com熱心網友回復:
幾乎接近。讓我們用 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;
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/443415.html
