Combine multiple rows into one space separated string

后端 未结 4 682
时光取名叫无心
时光取名叫无心 2020-12-30 05:05

So I have 5 rows like this

userid, col
--------------
1, a
1, b
2, c
2, d
3, e

How would I do query so it will look like this



        
4条回答
  •  轮回少年
    2020-12-30 05:33

    Use the GROUP_CONCAT aggregate function:

      SELECT yt.userid,
             GROUP_CONCAT(yt.col SEPARATOR ' ') AS combined
        FROM YOUR_TABLE yt
    GROUP BY yt.userid
    

    The default separator is a comma (","), so you need to specify the SEPARATOR of a single space to get the output you desire.

    If you want to ensure the order of the values in the GROUP_CONCAT, use:

      SELECT yt.userid,
             GROUP_CONCAT(yt.col ORDER BY yt.col SEPARATOR ' ') AS combined
        FROM YOUR_TABLE yt
    GROUP BY yt.userid
    

提交回复
热议问题