Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concat single column fields using GROUP BY

Tags:

hadoop

hive

Is there any way to combine/concat the fields within one column by grouping them. Eg:

col1   col2
1     aa
1     bb
1     cc
2     dd
2     ee

I want to query something like :

select col1, concat(col2) from tableName group by col1;

Output should be :

1    aa,bb,cc
2    dd,ee

Is there any function in hive to do this ?

like image 725
Arpit Gupta Avatar asked Jun 13 '14 06:06

Arpit Gupta


People also ask

How do I concatenate a column with multiple rows 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.

Can I use Concat with group by?

To concatenate strings in MySQL with GROUP BY, you need to use GROUP_CONCAT() with a SEPARATOR parameter which may be comma(') or space (' ') etc.

How do you concatenate values in a column?

We can perform the above activity using the CONCAT() function. CONCAT(): It takes column names as parameters and returns a column with value after concatenating all the values of the column passed parameters to the function.


1 Answers

you can use concat_ws() and collect_list() to achieve this....

Something like

select id , concat_ws(",", collect_list(val)) from test group by id; 

"," is the seperator in the above query.

like image 151
kanishka vatsa Avatar answered Nov 15 '22 04:11

kanishka vatsa