Concatenate JSON rows

▼魔方 西西 提交于 2021-01-28 20:09:21

问题


I have the following table with sample records:

create table jtest
(
    id int,
    jcol json
);

insert into jtest values(1,'{"name":"Jack","address1":"HNO 123"}');
insert into jtest values(1,'{"address2":"STREET1"}');
insert into jtest values(1,'{"address3":"UK"}');

select * from jtest;

id      jcol
-------------------------------------------
1       {"name":"Jack","address":"HNO 123 UK"}
1       {"address2":"STREET1"}
1       {"address3":"UK"}

Expected result:

id      jcol
--------------------------------------------------------------------------------------------
1       {"name":"Jack","address":"HNO 123 UK", "address2":"STREET1", "address3":"UK"}

Tried the following query:

select id,json_agg(jcol) as jcol
from jtest
group by id;

But getting result is unexpected:

id      jcol
--------------------------------------------------------------------------------------------
1       [{"name":"Jack","address":"HNO 123 UK"}, {"address2":"STREET1"}, {"address3":"UK"}] 

回答1:


demo:db<>fiddle

SELECT
    id,
    json_object_agg(key, value)      -- 2
FROM
    t,
    json_each(jcol)                  -- 1
GROUP BY id
  1. First you have to extract all elements into one row
  2. Afterwards you can reaggregate all of them


来源:https://stackoverflow.com/questions/65180882/concatenate-json-rows

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!