如何在PostgreSQL中用这样的数据concat一个数组?

gpfsuwkq  于 2023-08-04  发布在  PostgreSQL
关注(0)|答案(2)|浏览(123)

我想把所有对象的denominations连接起来,这些对象都是相同的id

[
  { id:1, details: { denominations : [ { code: "USD",value :100} ] } },
  { id:1, details: { denominations : [ { code: "USD",value :110} ] } },
  { id:2, details: { denominations : [ { code: "USD",value :100} ] } },
  { id:2, details: { denominations : [ { code: "USD",value :110} ] } }
]

字符串

[
  { id:1, details: { denominations : [ { code: "USD", value: 100 }, { code: "USD",value :110} ] } },
  { id:2, details: { denominations : [ { code: "USD", value: 100 }, { code: "USD",value :110} ] } }
]

8nuwlpux

8nuwlpux1#

这样就可以了,但是如果你的json文档有更多你没有显示的部分,那么你需要一个不同的方法:

with invars as (
  select '[
    { "id":1, "details": { "denominations" : [ { "code": "USD","value" :100} ] } },
    { "id":1, "details": { "denominations" : [ { "code": "USD","value" :110} ] } },
    { "id":2, "details": { "denominations" : [ { "code": "USD","value" :100} ] } },
    { "id":2, "details": { "denominations" : [ { "code": "USD","value" :110} ] } }
  ]'::jsonb as j
)
select jsonb_build_object(
         'id', e->>'id', 
         'details', jsonb_build_object(
                      'denominations', jsonb_agg(d.*)
                    )
       ) as result
  from invars i
       cross join lateral jsonb_array_elements(j) as e(top)
       cross join lateral jsonb_array_elements(e.top->'details'->'denominations') as d(detail)
 group by e->>'id';

字符串
工作fiddle

u2nhd7ah

u2nhd7ah2#

最好的答案取决于确切的细节。
要聚合第一个(仅?)数组元素从“denominations”跨整个输入,一个unnest就可以了:

SELECT jsonb_build_object('id', j.val -> 'id'
                        , 'details', jsonb_agg(j.val #> '{details,denominations,0}'))
FROM   tbl t, jsonb_array_elements(t.js) j(val)
GROUP  BY j.val -> 'id'
ORDER  BY j.val -> 'id';  -- optional

字符串
fiddle

相关问题