Reputation: 25
I have this input table:
T1
f1 f2
1 S1
1 S2
1 S3
2 S4
3 S5
3 S6
And need to produce this output table:
T2
g1 g2
1 S1+S2+S3
2 S4
3 S5+S6
S# values are strings. g1 is the grouped by value of f1. g2 is the concatenation of values f2.
Can I write a Postgres SQL statement to achieve this?
Upvotes: 0
Views: 20
Reputation: 1269793
Are you just looking for string_agg()
?
select f1, string_agg(f2, '+')
from t1
group by f1;
I don't really recommend string_agg()
unless you have a specific need for it. Arrays are more useful than strings:
select f1, array_agg(f2)
from t1
group by f1;
Also note that the ordering is not guaranteed for the elements in the string or array. You can add order by f2
if that is the ordering you want.
Upvotes: 1
Reputation: 222472
Use string_agg()
:
select f1, string_agg(f2, '+') f2s
from t1
group by f1
Upvotes: 1