Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine multiple rows into one space separated string

Tags:

sql

mysql

hive

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
like image 257
haoxu Avatar asked Sep 13 '10 19:09

haoxu


People also ask

How do I concatenate multiple rows into a single string in SQL?

You can concatenate rows into single string using COALESCE method. This COALESCE method can be used in SQL Server version 2008 and higher. All you have to do is, declare a varchar variable and inside the coalesce, concat the variable with comma and the column, then assign the COALESCE to the variable.


1 Answers

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?

like image 193
PanchaGil Avatar answered Oct 04 '22 00:10

PanchaGil