• 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的位置)且有序。

  • 相关阅读:
    HTML基础
    c++(11)构造函数、析构函数
    【被抛弃的程序员】和30岁“转行程序员”Say GoodBye
    宏集案例 | eX707G人机界面在石油钻井工程中的应用
    MCE 肿瘤代谢
    类和对象之 封装 继承 与 多态
    【实践篇】推荐算法PaaS化探索与实践
    安卓端App页面狂刷问题记录
    ant组件库 message组件只响应了一次就失效了
    电脑密码忘了怎么解除?最简单操作的方法
  • 原文地址:https://blog.csdn.net/z_ssyy/article/details/126300025