hive中的列转行和行转列


1、列转行

  1.1 相关函数的说明:

    concat(string1,string,...)  //连接括号内字符串,数量不限。

    concat_ws(separator,string1,string2,...)  //连接括号内字符串,数量不限,连接符为separator。

    collect_set(col)  //此函数只接受基本类型,主要是将字段的值进行去重汇总,产生array类型字段。

  1.2 例子:

  

   创建表:create table person_info(

        name string,

        constellation string,

        blood_type string

       )row format delimited fields terminated by '\t';

   上传数据:

    load data local inpath ‘/home/hdc/constellation.txt’ into table person_info;

   查询语句:

    select t.base,concat_ws('|',collect_set(t.name)) name

    from(

      select name,concat(costellation,',',blood_type) base

      from person_info

    )t

    group by t.base;

 

2、行转列

  2.1 相关函数:

    explode(col_name):将hive中的一列中复杂的array或者map分成多行

    lateral view:侧视图配合explode(或者其他的UDTF),一个语句生成把单行数据拆解成多行后的数据结果集。  //LATERAL VIEW explode(split(goods_id,','))goods相当于一个虚拟表

  2.2 例子:

  

  创建表:create table movie_info(

      name string,

      categroy array<string>

      )row format delimited fields terminated by '\t';

      collection items terminated by ',';

  上传数据:

    load data local inpath '/home/hdc/movie.txt' into table movie_info;

  查询语句:

    select name,category_type

    from movie_info lateral view explode(categroy) temp_table as category_type;

  解析:表movie_info与虚表temp_table进行笛卡尔乘积其中temp_table表中的字段为category_type

  explode还有如下用法:

  select distinct(t2.videoid), t3.category
        from (
            select explode(relatedid) as videoid
            from (
                select *
                from video_orc
                order by views desc
                limit 50) t1
         )t2

 

 

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM