Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgres - aggregate two columns into one item

I would like to aggregate two columns into one "array" when grouping.

Assume a table like so:

friends_map: ================================= user_id    friend_id    confirmed ================================= 1          2            true 1          3            false 2          1            true 2          3            true 1          4            false 

I would like to select from this table and group by user_id and get friend_id and confirmed as a concatenated value separated by a comma.

Currently I have this:

SELECT user_id, array_agg(friend_id) as friends, array_agg(confirmed) as confirmed FROM friend_map WHERE user_id = 1 GROUP BY user_id 

which gets me:

================================= user_id    friends      confirmed ================================= 1         [2,3,4]       [t, f, f] 

How can I get:

================================= user_id    friends      ================================= 1         [ [2,t], [3,f], [4,f] ] 
like image 773
SoluableNonagon Avatar asked Dec 08 '15 18:12

SoluableNonagon


People also ask

What is Array_agg in Postgres?

PostgreSQL ARRAY_AGG() function is an aggregate function that accepts a set of values and returns an array where each value in the input set is assigned to an element of the array. Syntax: ARRAY_AGG(expression [ORDER BY [sort_expression {ASC | DESC}], [...])

Is it possible to apply an aggregate function for each group in PostgreSQL?

For each group, you can apply an aggregate function e.g., SUM() to calculate the sum of items or COUNT() to get the number of items in the groups. In this syntax: First, select the columns that you want to group e.g., column1 and column2 , and column that you want to apply an aggregate function ( column3 ).

What is aggregate in Postgres?

Like most other relational database products, PostgreSQL supports aggregate functions. An aggregate function computes a single result from multiple input rows. For example, there are aggregates to compute the count , sum , avg (average), max (maximum) and min (minimum) over a set of rows.


1 Answers

SELECT user_id, array_agg((friend_id, confirmed)) as friends FROM friend_map WHERE user_id = 1 GROUP BY user_id  user_id |           array_agg             --------+--------------------------------       1 | {"(2,true)","(3,false)","(4,false)"} 
like image 99
Ivan Burlutskiy Avatar answered Oct 16 '22 00:10

Ivan Burlutskiy