YR.Park
YR.Park

Reputation: 1

How can I select datas to array in postgresql dbms?

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

Answers (1)

S-Man
S-Man

Reputation: 23676

demo: db<>fiddle

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
  1. Group the "groups" into a json array with json_agg
  2. The whole subquery rows can be converted into json objects with 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

Related Questions