Reputation: 1
Query result:
| student_id | name | age | group |
---------------+--------+-------+----------
| 1413001 | Ann | 14 | Tennis |
| 1413001 | Ann | 14 | Choir |
If I select records like this, I want to make them to JSON Object like
{student_id: "1413001", name: "Ann", Age: "14", group:["Tennis", "Choir"]}
How can I make them like that in Java or SQL?
Upvotes: 0
Views: 46
Reputation: 23676
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
row_to_json
https://www.postgresql.org/docs/current/static/functions-json.html
Notice that "group" is a reserved word in Postgres. I recommend to rename this column.
Upvotes: 1