Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to concatenate records based on a GROUP BY? [duplicate]

Tags:

sql

mysql

I have a table with a structure like:

| id | textfield | text_group | 
| 1  | yes       | 123        | 
| 2  | y         | 123        | 
| 3  | no        | abc        | 
| 4  | n         | abc        | 

I'd like to return all records, but such that I get:

| colA  | text_group | 
| yes y | 123        |
| no n  | abc        |

Is this possible simply with a query, or will I need to use some programming to format it as such? I would have done a group by, but then I lose the information in result ColA

like image 234
NinjaCat Avatar asked Oct 31 '25 03:10

NinjaCat


2 Answers

The group_concat aggregate function should do the trick:

SELECT   group_concat (textfield SEPARATOR ' ') AS colA, text_group
FROM     my_table
GROUP BY text_group
like image 103
Mureinik Avatar answered Nov 01 '25 17:11

Mureinik


Use GROUP_CONCAT :

SELECT text_group
     , GROUP_CONCAT(textfield SEPARATOR ' ') AS colA
FROM table
GROUP BY text_group
like image 41
potashin Avatar answered Nov 01 '25 17:11

potashin