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

标签 sql json postgresql

使用 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/

相关文章:

java.sql.SQLException : Parameter number 2 is not an OUT parameter

sql - 没有子查询的表的多次传递

json - 如何使用 VBScript 通过 HTTP API POST JSON 数据?

postgresql - "mount"来自非备份文件的 PostgreSQL 数据库

mysql - 选择在两天内有操作的用户,其中一天在上周内

mysql - 根据时间跨度获取正确的行

json - Swift 和 Alamofire API 调用 : trouble reading parameters

json - 使用 ngFor-Loop (Angular) 显示 JSON

postgresql - 在 phpPgadmin 中创建程序

php - 无论如何要告诉 postgres 数组中的数据类型?