hive的concat、concat_ws和collect_list、collect_set的用法
- concat和concat_ws
- collect_list和collect_set
concat和concat_ws
concat():函数在连接字符串的时候,只要其中一个是NULL,那么将返回NULL。
执行代码: select concat('a','b',null); 执行结果: NULLconcat_ws():函数在连接字符串的时候,只要有一个字符串不是NULL,就不会返回NULL。concat_ws():函数需要指定分隔符。
执行代码1: select concat_ws('-','a','b'); 执行结果: a-b 执行代码2: select concat_ws('-','a','b',null); 执行结果: a-b 执行代码3: select concat_ws('','a','b',null); 执行结果: abcollect_list和collect_set
他们都是将分组中的某列转为一个数组返回,不同的是collect_list不去重,而collect_set去重。
最终的返回值:
(1)collect_list():有序不去重
(2)collect_set():无序去重
原始数据:

collect_set示例代码:
select t.id, concat_ws(',', collect_set(t.class)) from temp t group by t.id实际结果:

可以发现,collect_set合并后并不是有序。
collect_list示例代码:
select t.id, concat_ws(',', collect_list(t.class)) from temp t group by t.id实际结果:

collect_list合并后有序。
在spark_sql中,将collect_list的类型转化为string,只需要使用cast函数,但是在离线平台中,是不支持Array转化为string,所以需要借助:concat_ws。
在聚合字段时,查询时将collect_list前使用concat_ws函数,这样该字段就转化为string了。
concat_ws(',', collect_list(t.class))若是想使用collect_set使结果有序,可以采用:
select t.id, concat_ws(',', sort_array(collect_set(t.class), false)) from temp t group by t.idsort_array(e: column, asc: boolean)将array中元素排序(自然排序),默认asc。
实际结果:

猜你喜欢
网友评论
- 搜索
- 最新文章
- 热门文章
