Search code examples
mysqlsqljointemp-tables

MySQL to group a column's values to a single cell value


I have a query that return data with 10 columns and in which only one column value is unique for every row and all the other column values will be repeated for few rows each.

Eg: Column 1 | Column 2 | column 3 | column 4 | column 5 | Column 6
          Sony     |    Xperia   |   stack      |   ask        | question   |    XYZ
          Sony     |    Xperia   |   stack      |   ask        | question   |    ABC
          Sony     |    Xperia   |   stack      |   ask        | question   |    123
          Nexus   |   Android  |   stack      |   ask        | question   |    POI
          Nexus   |   Android  |   stack      |   ask        | question   |    KILL

I want the result to be as -

Eg: Column 1 | Column 2 | column 3 | column 4 | column 5 | Column 6
          Sony     |    Xperia   |   stack      |   ask        | question   |    XYZ, ABC, 123
          Nexus   |   Android  |   stack      |   ask        | question   |    POI, KILL

Can you guys please help me in achieving this through mysql query ?? Just a hint of the possibilities would do. I got the values in sorted order so that the "to be grouped" rows will always come consecutively.

Thanks in advance. :)


Solution

  • You do this using aggregation and group_concat():

    select column1, column2, column3, column4, column5, group_concat(column6) as column6
    from query q
    group by column1, column2, column3, column4, column5;