hive行列转换总结

hive行列转换方法

具体思路需要根据数据来定,常见的解决方法如下:

行转列: 多行转多列

1、使用case when 查询出多列即可,即可增加列。
或者
2.转成数组或者集合后 一个一个的取值 不就变成一列了
一个字段 多个取值 变成多列
多列变一列
select concat(str1,str2,str3) from 表; – concat可以带多个参数

列转行: 字段 多行转一行 一行转多行

1、lateral view explode(),使用炸裂函数可以将1列转成多行,被转换列适用于array、map等类型。lateral view posexplode(数组),如有排序需求,则需要索引。将数组炸开成两行(索引 , 值),需要as 两个别名。
2、case when 结合concat_ws与collect_set/collect_list实现。内层用case when,外层用collect_set/list收集,对搜集完后用concat_ws分割连接形成列。

注意 对习题二的分析
如果使用了case when 就不能分组
select id,
case when c.course=‘a’ then 1 else 0 end a,
case when c.course=‘b’ then 1 else 0 end b,
case when c.course=‘c’ then 1 else 0 end c,
case when c.course=‘d’ then 1 else 0 end d,
case when c.course=‘e’ then 1 else 0 end e,
case when c.course=‘f’ then 1 else 0 end f
from course c
在这里插入图片描述
要想使用分组就得用sum()
select id,
sum(case when c.course=‘a’ then 1 else 0 end) as a,
sum(case when c.course=‘b’ then 1 else 0 end) as b,
sum(case when c.course=‘c’ then 1 else 0 end) as c,
sum(case when c.course=‘d’ then 1 else 0 end) as d,
sum(case when c.course=‘e’ then 1 else 0 end) as e,
sum(case when c.course=‘f’ then 1 else 0 end)as f
from course c
group by id
在这里插入图片描述

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值