Postgres转换具有重复ID的JSON

3

使用此选择:

json_agg(json_build_object("id", price::money))

我得到了结果值:
[
  {"6" : "$475.00"}, 
  {"6" : "$1,900.00"},
  {"3" : "$3,110.00"},
  {"3" : "$3,110.00"}
]

我希望数据使用这种格式呈现:
{
  "6": ["$475.00","$1,900.00"],
  "3": ["$3,110.00","$3,110.00"]
}

当在服务器上查询或与jsonb一起使用时,ID会重复,只有一个键值对能够通过。


也许[array_agg(price :: money)](https://www.postgresql.org/docs/current/functions-aggregate.html)可以解决它,但如果没有示例数据,有点难以确定。 - Raymond Nijland
1个回答

5
你应该按照id将价格分组并使用聚合函数json_object_agg()。由于聚合无法嵌套,所以必须使用派生表(在from子句中的子查询):
select json_object_agg(id, prices)
from (
    select id, json_agg(price::money) as prices
    from my_table
    group by id
    ) s

rextester上的工作示例。


所有内容都包含在一个数组中:[{"6" : ["$475.00", "$1,900.00"]}, {"3" : ["$3,110.00", "$3,110.00"]}],我希望它只是一个对象:{"6" : ["$475.00", "$1,900.00"], "3" : ["$3,110.00", "$3,110.00"]} - that_guy
我意识到我的问题格式错误了,我已经编辑过来反映那个评论。抱歉! - that_guy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接