hive 高级数据类型使用之array(含横表转纵表)

hive 高级数据类型使用

用了许久的hive,但是一直都是简单的sql join,sort, order by等,今天有一个业务场景需要使用array数据类型存储数据并进行横表转纵表的转换。mark下以后用了可以查询。 
数据样子是这样的。

IDtype_flagtags
10001311_20_30,11_22_34,12_23_30,13_24_36
10002211_20,11_22,12_23,13_24
10003111,12

表格1

需要转化成的样子如下:

IDtype_flagtag1tag2tag3
100013112030
100013112234
100013122330
100013132436
1000221120 
1000221122 
1000221223 
1000221324 
10003111  
10003112  

表格2

  • 创建表tmp_type_tags存储表格1的数据
create table tmp.tmp_type_tags
(
        id bigint       ,
        type_flag string,
        tags array < string >
)
row format delimited fields terminated by '\t' 
COLLECTION ITEMS TERMINATED BY ',' stored as textfile;
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 创建表tmp_type_tag_split存储转化中间的数据
create table tmp.tmp_type_tag_split
(
        id bigint       ,
        type_flag string,
        tag array < string >
)
row format delimited fields terminated by '\t' 
COLLECTION ITEMS TERMINATED BY '_' stored as textfile;
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 第一步横转纵 
    将数据按照第一层分隔符,转化成数据size那么多的行数。sql如下
insert overwrite table tmp.tmp_type_tag_split
select
        id       ,
        type_flag,
        split(tag0, '_')
from
        tmp.tmp_type_tags lateral view explode(tags) r1 as tag0
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

数据结果: 
tmp_type_tag_split数据

  • 第二步按照类型进行分列
 create table tmp.tmp_type_tag_split_info as 
 select
  id       ,
  type_flag,
  (case when type_flag in(1, 2, 3) then tag[0] else '' end) as tag1,
  (case when type_flag in(2, 3) then tag[1] else '' end) as tag2,
  (case when type_flag in(3) then tag[2] else '' end) as tag3
 from
     tmp.tmp_type_tag_split
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

最终表数据结果如下:转换完成 
最终结果

来自: https://blog.csdn.net/dreamingfish2011/article/details/51250641
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值