我将PostgreSQL表中每一行的数据存储在JSON数组中,如下所示:

id          data
-------------------------------------------------
1           [{"a": 1, "b": 2}, {"a": 3, "b":2}]
2           [{"a": 5, "b": 8}, {"a": 9, "b":0}]

如何获取按id分组的记录集中特定键的总和?
下面是所需结果集的示例:
id          a           b
-------------------------------------------------
1           4           4
2           14          8

更新:
我还应该提到数据列是jsonb数据类型。

最佳答案

select id, sum(a), sum(b)
  from jsontable j
    CROSS JOIN LATERAL
    json_to_recordset(j.data) as x(a integer, b integer)
group by id

在这里,您可以测试查询或修改它http://rextester.com/ZTCY82930
有关json-to-u记录集的文档,请参见https://www.postgresql.org/docs/9.6/static/functions-json.html
至于交叉连接,请看这个https://www.reddit.com/r/PostgreSQL/comments/2u6ah3/how_to_use_json_to_recordset_on_json_stored_in_a/co6hr65/
编辑:正如您在更新中所说,您使用一个jsonb字段,因此不使用json_to_recordset,只使用jsonb_to_recordset

09-04 06:13
查看更多