gpt4 book ai didi

sql - Postgres : row with comma separated value to array of json objects

转载 作者:行者123 更新时间:2023-11-29 12:50:16 24 4
gpt4 key购买 nike

使用 postgres 9.4。

数据:

+-----+------+
| id | type |
+-----+------+
| 1 | A |
+-----+------+
| 2,3 | A |
+-----+------+
| 4 | B |
+-----+------+

期望的输出(JSON):

[
[{"id": "1", "type": "A"}],
[{"id": "2", "type": "A"},{"id": "3", "type": "A"}],
[{"id": "4", "type": "B"}]
]

我试过:

SELECT array_to_json(array_agg(c)) 
FROM
(
SELECT
regexp_split_to_table(id, ',') AS id,
type
FROM my_table
) c;

这让我得到一个简单的 json 对象数组:

[
{"id": "1", "type": "A"},
{"id": "2", "type": "A"},
{"id": "3", "type": "A"},
{"id": "4", "type": "B"}]
]

如何将子查询的每个结果集(而不是每一行)包装在一个数组中?

最佳答案

我相信这可以满足您的需求:

with t as (
select *
from (values ('1', 'A'), ('2,3', 'A'), ('4', 'B')) v(ids, type)
)
select json_agg(c)
from (select array_to_json(array_agg( json_build_object('id', c.id, 'type', c.type))) as c
from (select ids, regexp_split_to_table(ids, ',') AS id, type
from t
) c
group by ids
) i;

Here是一个数据库<> fiddle 。

关于sql - Postgres : row with comma separated value to array of json objects,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55810120/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com