查询结果:
| student_id | name | age | group |
---------------+--------+-------+----------
| 1413001 | Ann | 14 | Tennis |
| 1413001 | Ann | 14 | Choir |
如果我选择这样的记录,我想将它们设置为JSON Object
{student_id: "1413001", name: "Ann", Age: "14", group:["Tennis", "Choir"]}
如何在Java或SQL中使它们像这样?
答案 0 :(得分:1)
SELECT
row_to_json(s)
FROM (
SELECT
student_id,
name,
age,
json_agg("group") as "group"
FROM students
GROUP BY student_id, name, age
) s
json_agg
将“组”分组为一个json数组row_to_json
将整个子查询行转换为json对象https://www.postgresql.org/docs/current/static/functions-json.html
请注意,“组”是Postgres中的保留字。我建议重命名此列。