Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL - sort alphabetically for strings within a column

Tags:

postgresql

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

like image 499
J.YC.Murtaught Avatar asked Nov 19 '22 02:11

J.YC.Murtaught


1 Answers

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;
like image 169
Patrick Avatar answered Dec 28 '22 16:12

Patrick