hive中实现group_concat

mysql中的group_concat分组连接功能相当强大,可以先分组再连接成字符串,还可以进行排序连接。但是hive中并没有这个函数,那么hive中怎么实现这个功能呢?

这里要用到:concat_ws函数和collect_list、collect_set 函数。

  1. 建立测试表(无分区表):
create table if not exists db_name.test_tb(
	id string,
	content string,
	comment string
) row format delimited 
fields terminated by '\1' 
stored as textfile;
  1. 插入几条数据:
insert into db_name.test_tb values('1','Tom','测试1');
insert into db_name.test_tb values('1','Bob','测试2');
insert into db_name.test_tb values('1','Wendy','测试3');
insert into db_name.test_tb values('2','Bob','测试22');
insert into db_name.test_tb values('2','Tom','测试11');
  1. concat_ws + collect_set + group by:
select
    id,
    concat_ws(',',collect_set(content)) as con_con,
    concat_ws(',',collect_set(comment)) as con_com
from db_name.test_tb
group by id;

结果:无序且不对应(con_con与con_com的位置) —— 但是注意 collect_set会将重复的数据删除,因为集合的性质。
每次运行连接的结果顺序都可能不一样。

  1. concat_ws + collect_list + group by:
select
    id,
    concat_ws(',',collect_list(content)) as con_con,
    concat_ws(',',collect_list(comment)) as con_com
from db_name.test_tb
group by id;

结果:对应(con_con与con_com的位置)但无序。

  1. concat_ws + collect_list + group by + row_number():
select
    id,
    concat_ws(',',collect_list(content)) as con_con,
    concat_ws(',',collect_list(comment)) as con_com,
    concat_ws(',',collect_list(cast(rn as string))) as con_rn
from 
(
select
    id,
    content,
    comment,
    row_number() over(partition by id order by content asc) as rn
from db_name.test_tb
)
group by id;

结果:对应(con_con与con_com的位置)且有序。

  • 5
    点赞
  • 42
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

雾岛与鲸

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值