zoukankan      html  css  js  c++  java
  • Hive学习笔记:列转行之collect_list/collect_set/concat_ws

    一、介绍

    Hive 中想实现按某字段分组,对另外字段进行合并,可通过 collect_list 或者 collect_set 实现。

    它们都是将分组中的某列转为一个数组返回,其中区别在于:

    • collect_list -- 不去重
    • collect_set -- 去重

    有点类似于 Python 中的列表、集合。

    二、实操

    1.创建测试表

    create table table_tmp(
        id string,
        classes string
    ) partitioned by (month string)
    row format delimited fields terminated by ',';
    

    2.本地文件

    1,a
    1,b
    2,a
    2,b
    2,a
    2,c
    3,a
    3,c
    

    3.数据加载Hive表

    load data local inpath '/root/data/id.data' into table table_tmp partition (month='202201');
    

    4.分组

    select id,
           collect_list(classes) as col_001
    from table_tmp
    group by id;
    

    5.concat_ws + collect_list 实现不去重合并

    select id,
           concat_ws('-', collect_list(cast(col_001 as string))) as col_concat
    from table_tmp
    group by id;
    

    6.concat_ws + collect_set 实现去重合并

    select id,
           concat_ws('-', collect_set(cast(col_001 as string))) as col_concat
    from table_tmp
    group by id;
    

    三、其他

    1.突破group by限制

    可以利用 collect 突破 group by 的限制,分组查询的时候要求出现在 select 后面的列都必须是分组的列。

    但有时候我们想根据某列进行分组后,随机抽取另一列中的一个值,即可通过以下实现:

    select id
           collect_list(classes)[0] as col_001
    from table_tmp
    group by id;
    

    有种类似于 Python 中索引切片的感觉。

    2.concat_ws语法

    concat_ws(separator, str1, str2, ...)
    concat_ws(separator, [str1, str2, ...])
    

    参考链接:hive中对多行进行合并—collect_set&collect_list函数

    参考链接:Hive笔记之collect_list/collect_set(列转行)

  • 相关阅读:
    day06_02 继承
    day06_03 多继承区别
    day03_04 字符集编码转换
    day04_03 序列化与反序列化
    day04_06 单线程生成器的并行效果(协程)
    day04_02 装饰器 高阶版
    day04_05 内置方法
    复合控件的开发心得
    从子节点找父节点的循环sql
    asp中试用存储过程
  • 原文地址:https://www.cnblogs.com/hider/p/15790494.html
Copyright © 2011-2022 走看看