将多行合并为一个空格分隔的字符串

发布于 2024-09-19 11:50:08 字数 185 浏览 6 评论 0原文

所以我有 5 行像这样

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

我将如何进行查询,所以它看起来像这样

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

亢潮 2024-09-26 11:50:27
  1. MySQL 包含重复项: select col1, group_concat(col2) from table1 group by col1
  2. MySQL 不包含重复项: select col1, group_concat(distinct col2) from table1 group by col1
  3. Hive 包含重复项: select col1,collect_list(col2) from table1 group by col1
  4. Hive without重复:select col1,collect_set(col2) from table1 group by col1
  1. MySQL with duplicates: select col1, group_concat(col2) from table1 group by col1
  2. MySQL without duplicates: select col1, group_concat(distinct col2) from table1 group by col1
  3. Hive with duplicates: select col1, collect_list(col2) from table1 group by col1
  4. Hive without duplicates: select col1, collect_set(col2) from table1 group by col1
懒猫 2024-09-26 11:50:24
SELECT 
  userid,
  concat_ws(" ", collect_set(col)) AS combined
FROM table 
GROUP BY userid
SELECT 
  userid,
  concat_ws(" ", collect_set(col)) AS combined
FROM table 
GROUP BY userid
回首观望 2024-09-26 11:50:21

使用GROUP_CONCAT聚合函数

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

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

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

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

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
始终不够 2024-09-26 11:50:19

在hive中你可以使用

SELECT userid, collect_set(combined) FROM tabel GROUP BY user_id;

collect_set删除重复的。如果您需要保留它们,可以查看这篇文章:

COLLECT_SET() in Hive, keep duplicates ?

In hive you can use

SELECT userid, collect_set(combined) FROM tabel GROUP BY user_id;

collect_set removes duplicated. If you need to keep them you can check this post:

COLLECT_SET() in Hive, keep duplicates?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文