postgresql - Postgres: aggregate column into array -


i have following 2 tables:

# select * list;   list_id |         name  ---------+----------------------         9 | popular        11 | recommended 

and

# select * list_item;  list_id | game_id | position  ---------+---------+----------       11 |       2 |        0        9 |      10 |        1       11 |       5 |        1       11 |       4 |        4       11 |       6 |        2       11 |       7 |        3        9 |       3 |        0 

i want array of game ids per list so:

 list_id |     name    | game_ids ---------+-------------+------------        9 | popular     | {3,10}       11 | recommended | {2,5,6,7,4} 

i came following solution seems rather complicated bit completed array using distinct on , last_value:

with w (   select     list_id,     name,     array_agg(game_id) on (partition list_id order position)   list   join list_item   using (list_id) ) select   distinct on (list_id)   list_id,   name,   last_value(array_agg) on (partition list_id) w 

any suggestions how simplify this?

here better solution suggested abelisto in comments:

select   list_id,   name,   array_agg(game_id order position) list join list_item using (list_id) group list_id, name 

Comments