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] ]
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}], [...])
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 ).
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.
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)"}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With