Duong Tuan Nhat
Duong Tuan Nhat

Reputation: 39

group by column and select other column as list in rails

I have a table like bellow

+---+---+
| A | B |
+---+---+
| 1 | 1 |
+---+---+
| 2 | 1 |
+---+---+
| 3 | 2 |
+---+---+
| 4 | 2 |
+---+---+
| 5 | 2 |
+---+---+

Is there an effective way to query to form like:

{1 => [1,2], 2 => [3,4,5]}

(group by B and select A as list)

Upvotes: 1

Views: 156

Answers (1)

Fahmi
Fahmi

Reputation: 37473

you can use string_agg() function

select B,string_agg(A,', ') 
from tablename
group by B

OR you can use array_agg()

select B,array_agg(A) 
from tablename
group by B

Upvotes: 1

Related Questions