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

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

问题描述

所以我有这样的 5 行

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

推荐答案

使用 GROUP_CONCAT 聚合函数:

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

默认的分隔符是逗号(","),所以你需要指定单个空格的 SEPARATOR 才能得到你想要的输出.

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

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

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天全站免登陆