Reputation: 51
I am working with postgresql and I have a table like this:
Group | Name
======================================
1 | Mary
2 | Barry,Ann,Peter
3 | Max,Chris
4 | Richard,Mary,Peter,Oliver
The table is an example, you can consider there will be more than 10,000 different names, the max number of names in one group is 4.
I want to sort the name within each group alphabetically so the result would be like this:
Group | Name
======================================
1 | Mary
2 | Ann,Barry,Peter
3 | Chris,Max
4 | Mary,Peter,Oliver,Richard
Thanks
Upvotes: 5
Views: 1260
Reputation: 32179
SELECT t.Group, string_agg(n.names, ',' ORDER BY n.names) AS Name
FROM my_table t,
regexp_split_to_table(t.Name, ',', 'g') n(names)
GROUP BY 1
ORDER BY 1;
Upvotes: 1