F
F
fr0zen2017-03-16 09:24:29
PostgreSQL
fr0zen, 2017-03-16 09:24:29

How to group records in Postgres?

There is an example
sqlfiddle.com/#!15/c2f3f/18
How to refine the query so that there are 3 records left, 1 for each record from table1, so that the skills field contains an array of corresponding values ​​from table2, that is:
1 asya [ burn, eat ]
2 petya [code]
3 lena [cook, clean]

Answer the question

In order to leave comments, you need to log in

3 answer(s)
M
Maxim Fedorov, 2017-03-16
@fr0zen

use the array_agg function like so:

SELECT table1 .id, table1 .name, array_agg(table2.skills)
FROM table1 
LEFT JOIN table2 ON table2.id = table1.id
GROUP BY table1.id

S
Sergey Gornostaev, 2017-03-16
@sergey-gornostaev

First, you don't need union, use join . Second, grouping is done with group by . To get an array of grouped values, use the array_agg() aggregate function .

select
  t1.name, array_agg(t2.skills)
from table1 as t1
inner join table2 as t2
  using (id)
group by t1.name;

sql fidle

L
Leonid, 2017-03-16
@zzevaka

SELECT id, name, array_agg(skills)
FROM table1 JOIN table2 USING (id)
GROUP BY 1,2

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question