汇总JSON值

时间:2019-07-18 04:20:05

标签: json postgresql sum

有什么办法让我从一列中读取json数据,并根据其键将这些值相加并排列它们。该列的示例是:

id_column | json_data
1         | {"A": 1, "C": 4, "D": -2}
2         | {"B": 3, "S": 0, "A": 2, "D": 0}

我想要得到的最终结果应如下所示:

json_data
{"A": 3, "B": 3, "C": 4, "D": -2, "S": 0}

所以最终结果实际上是每行json数据的总和,而且键是从A-Z排列的。

1 个答案:

答案 0 :(得分:2)

该方法如下:

SELECT json_object_agg(key, val ORDER BY key)
FROM (SELECT t.key,
             sum(CAST(t.val AS bigint)) AS val
      FROM j
         CROSS JOIN LATERAL jsonb_each_text(j.json_data)
                            AS t(key, val)
      GROUP BY t.key
     ) AS q;

                 json_object_agg                  
--------------------------------------------------
 { "A" : 3, "B" : 3, "C" : 4, "D" : -2, "S" : 0 }
(1 row)

jsonb中没有顺序,因此我将json用于结果。