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

2. 插入几条数据:

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')

3. 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会将重复的数据删除,因为集合的性质。

每次运行连接的结果顺序都可能不一样。

4. 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的位置)但无序。

5. 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 db_name.test_tb
(
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的位置)且有序。

 

#

https://www.cnblogs.com/zhangqian27/p/12836126.html

https://blog.csdn.net/changzoe/article/details/81181820

posted on   落日峡谷  阅读(18676)  评论(0编辑  收藏  举报

编辑推荐:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示