Postgres 转换具有重复 ID 的 json

tha*_*guy 3 postgresql json aggregate-functions

通过此选择:

json_agg(json_build_object("id", price::money))
Run Code Online (Sandbox Code Playgroud)

我得到的结果值:

[
  {"6" : "$475.00"}, 
  {"6" : "$1,900.00"},
  {"3" : "$3,110.00"},
  {"3" : "$3,110.00"}
]
Run Code Online (Sandbox Code Playgroud)

我想要这种格式的数据:

{
  "6": ["$475.00","$1,900.00"],
  "3": ["$3,110.00","$3,110.00"]
}
Run Code Online (Sandbox Code Playgroud)

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

kli*_*lin 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
Run Code Online (Sandbox Code Playgroud)

rextester 中的工作示例。