Search code examples
mysqlsqlgroup-concat

Select Multiple rows in single column separated by New Line


I have a table with values look like this.

    Id Name Fruit
    ------------
    1 Jon  Apple
    ------------
    2 Jon  Orange
    ------------
    3 Jon  Grape
    ------------
    4 Mike Apple
    ------------
    5 Mike Orange
    -------------

How to distinct the column into something like this in mysql?

    Name Fruit
    ----------
    Jon  Apple
         Orange
         Grape
    -----------
    Mike Apple
         Orange
    -----------

Solution

  • This should do

    SELECT name, GROUP_CONCAT(fruit SEPARATOR '\n') FROM your_table GROUP BY name
    

    Demo in db<>fiddle

    Update to add numbering:

    SELECT name ,
           GROUP_CONCAT(CONCAT (rn,')',fruit) SEPARATOR '\n')
    FROM (
        SELECT * 
            ,ROW_NUMBER() OVER (PARTITION BY name) AS rn
        FROM your_table
        ) SQ
    GROUP BY name
    

    Demo with numbering in db<>fiddle