Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sql string cat as aggregate function: cat multiple records together

Tags:

sql

mysql

I have a table with columns: (project_id, name)

It's a list of people, each one with the project it belongs to. If a person is in two projects, it is duplicated.

I want to extract a table with columns: (project_id, people) where people is a string cat of the names of all person working on that project. The cat must be comma separated, like this:

12, john
12, mark
12, dave
14, luke

becomes

12, "john, mark, dave"
14, "luke"
like image 471
luca Avatar asked Feb 24 '23 04:02

luca


1 Answers

you can do this with a simple query

SELECT project_id, GROUP_CONCAT(name) as people
FROM table
GROUP BY project_id

if you insist to have space after the comma:

SELECT project_id, GROUP_CONCAT(name SEPARATOR ", ") as people
FROM table
GROUP BY project_id
like image 164
Teneff Avatar answered Feb 26 '23 20:02

Teneff