将多行组合成一个空格分隔的字符串 [英] Combine multiple rows into one space separated string

查看:156
本文介绍了将多行组合成一个空格分隔的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



我会如何进行查询,因此它看起来像这样

  userid,合并
1,ab
2,cd
3,e


解决方案

使用 GROUP_CONCAT聚合函数

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

默认分隔符是一个逗号(,),因此您需要指定单个空格的SEPARATOR来获得您想要的输出。



如果要确保GROUP_CONCAT中值的顺序,请使用:

  SELECT yt.userid,
GRO UP_CONCAT(yt.col ORDER BY yt.col SEPARATOR'')AS as
FROM YOUR_TABLE yt
GROUP BY yt.userid


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

userid, combined
1, a b
2, c d
3, e

解决方案

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

这篇关于将多行组合成一个空格分隔的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆