P
P
Peter2017-03-22 15:05:00
PostgreSQL
Peter, 2017-03-22 15:05:00

How to form a selection into an array of duplicate records?

The table has a unique id, there is a user id and a value from 1 to 6 that he chose.
id | id_user | data
----+-----------+-------
1 | 1456 | 6
2 | 5812 | 2
3 | 1456 | 1
4 | 1456 | 5
5 | 5812 | 3
6 | 7774 | 1
I need to make a selection so that the user's id and an array of all the values ​​\u200b\u200bchosen by him for the entire time would be obtained.

[
    {
        id_user: 1456,
        data: [6, 1, 5],
    },
    {
        id_user: 5812,
        data: [2,3]
    },
    {
        id_user: 7774,
        data: [1]
    }
]

What should the query look like for this solution?
Thanks in advance!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Melkij, 2017-03-22
@volkov_p_v

select id_user, array_agg(data) from tablename group by id_user

You can immediately collect json. With an eye on the database version only.
select json_agg((
select json_build_object('id_user', id_user, 'data', json_agg(data)) from tablename group by id_user
));

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question