Monday, 20 March 2017

mysql - How to concatenate records based on a GROUP BY?





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


Answer



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

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...