【问题标题】:Calculate sum for items in nested jsonb array计算嵌套 jsonb 数组中项目的总和
【发布时间】:2021-04-20 10:20:07
【问题描述】:

所以我有 Postgres DB 表“购买”,其中包含“id”和“receipt”列。 'id' 是主 int 列,'receipt' 列中的值是 jsonb,可以如下所示:

{
  "shop_name":"some_shop_name", 
  "items": [
    {
      "name": "foo", 
      "spent": 49,
      "quantity": 1
    },     
    {
      "name": "bar", 
      "price": 99,
      "quantity": 2
    },
    {
      "name": "abc", 
      "price": 999,
      "quantity": 1
    },
    ...
  ]
}

收货的数量可以不同。

最后我需要编写一个查询,以便生成的表包含表中每次购买的所有bar上的购买ID和金额:

id spent
1 198
.. ...

我的问题:

我不知道如何在结果表中沿常规列的 select 查询中使用 jsonb,我猜查询的结构应该是这样的:

SELECT p.id, %jsonb_parsing_result_here% AS spent
FROM purchases p 

这阻止了我在 FOR 循环中迭代项目(或者可能使用其他方式)进一步移动。

【问题讨论】:

    标签: postgresql for-loop sum jsonb


    【解决方案1】:

    您可以使用横向连接和jsonb_array_elements 函数从receipt 列中取消嵌套items,例如:

    SELECT p.id, SUM((item->>'price')::NUMERIC)
    FROM purchases p,
    LATERAL jsonb_array_elements(p.receipt->'items') r (item)
    GROUP BY p.id
    

    也可以添加where条件,例如:

    WHERE item->>'name' = 'bar
    

    【讨论】:

      猜你喜欢
      • 2020-12-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-05
      • 2022-10-09
      • 1970-01-01
      • 2021-05-18
      相关资源
      最近更新 更多