连接 JSON 行
Concatenate JSON rows
我有以下 table 示例记录:
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"}
预期结果:
id jcol
--------------------------------------------------------------------------------------------
1 {"name":"Jack","address":"HNO 123 UK", "address2":"STREET1", "address3":"UK"}
尝试了以下查询:
select id,json_agg(jcol) as jcol
from jtest
group by id;
但是得到的结果出乎意料:
id jcol
--------------------------------------------------------------------------------------------
1 [{"name":"Jack","address":"HNO 123 UK"}, {"address2":"STREET1"}, {"address3":"UK"}]
SELECT
id,
json_object_agg(key, value) -- 2
FROM
t,
json_each(jcol) -- 1
GROUP BY id
- 首先你必须将所有元素提取到一行中
- 之后您可以重新聚合所有这些
我有以下 table 示例记录:
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"}
预期结果:
id jcol
--------------------------------------------------------------------------------------------
1 {"name":"Jack","address":"HNO 123 UK", "address2":"STREET1", "address3":"UK"}
尝试了以下查询:
select id,json_agg(jcol) as jcol
from jtest
group by id;
但是得到的结果出乎意料:
id jcol
--------------------------------------------------------------------------------------------
1 [{"name":"Jack","address":"HNO 123 UK"}, {"address2":"STREET1"}, {"address3":"UK"}]
SELECT
id,
json_object_agg(key, value) -- 2
FROM
t,
json_each(jcol) -- 1
GROUP BY id
- 首先你必须将所有元素提取到一行中
- 之后您可以重新聚合所有这些