json - json数组的总和

标签 json postgresql

我有 json 类型的字段,像这样

数据

{"age": 44, "name": "Jun"}

{"age": 19, "name": "Pablo", "attempts": [11, 33, 20]}

{"age": 33, "name": "Maria", "attempts": [77, 10]}

这里有些 json 数据有“attempts”数组,有些则没有。当 json 有这个数组时,我需要得到不同字段中数组元素的总和,需要像这样的结果

数据,sum_of_array

{"age": 44, "name": "Jun"} , (nothing here)

{"age": 19, "name": "Pablo", "attempts": [11, 33, 20]} , 64

{"age": 33, "name": "Maria", "attempts": [77, 10]} , 87

最佳答案

SELECT attempts.id,
       sum(vals.v::integer) sum_attempts
FROM attempts
   LEFT JOIN LATERAL jsonb_array_elements_text(val->'attempts') vals(v)
      ON TRUE
GROUP BY attempts.id;

如果您使用 json 而不是 jsonb,请使用 json_array_elements_text

关于json - json数组的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43277178/

相关文章:

ios - 如何提取内部响应值并将其传递给UserModel

ios - JSON 到 NSDictionary。不应该这么难吗?

ruby-on-rails - 在 JSON/XML 中呈现非 activerecord 对象 [RoR]

mysql - SQL 检测 OR 子句中的元素

sql - 如何在 Postgresql 中加入 array_agg 列的 View ?

ruby-on-rails - rails : An efficient method to match subdomains in the database?

java - 使用 volley 从 php 页面发送和接收

javascript - Angular js - json 上的简单循环不起作用

macos - 无法从 BASH 脚本中运行 psql 命令

ruby-on-rails - rails docker-compose db :create db:migrate 的最佳实践