hive-行转列列转行

一、

 

idstype
1A
1C
1E
2B
2D
2F

 

idsABCDEF
1101010
2010101

将第一个表格的数据变成第二种

两种方式:1. 

 select ids, 
 count(if(type='A',1,null))A,
 count(if(type='B',1,null))B,
 count(if(type='C',1,null))C,
 count(if(type='D',1,null))D,
 count(if(type='E',1,null))E,
 count(if(type='F',1,null))F from lp.study group by ids;

2.

 select ids,sum(if(type='A',1,0))A,
 sum(if(type='B',1,0))B,
 sum(if(type='C',1,0))C,
 sum(if(type='D',1,0))D,
 sum(if(type='E',1,0))E,
 sum(if(type='F',1,0))F from lp.study group by ids;

 

二.行转列 使用 collect_set

 

idstype
1A
1C
1E
2B
2D
2F

 

idstype
1A,C,E
2B,D,F

将第一个表格转为第二个表格

 

select ids,concat_ws(",",collect_set(type)) types  from lp.study group by ids;

执行下个句子了解

select ids,concat_ws(',',collect_set(type)) types
from
(
select '1' ids,'A' type
union all
select '1' ids,'B' type
union all
select '1' ids,'C' type
union all
select '2' ids,'E' type
union all
select '2' ids,'F' type
union all
select '2' ids,'D' type
) a
group by ids;

三.列传行 使用 lateral view explode

idstype
1A,C,E
2B,D,F

 

idstype
1A
1C
1E
2B
2D
2F

将第一个表格转为第二个表格

select ids,type from 
 (select ids,concat_ws(",",collect_set(type)) types  from lp.study group by ids) a lateral view explode(split(types,",")) col as type ;

执行下面这个句子了解

select ids,type from
(
select '1' ids,'A,B,C' types
union all
select '2' ids,'D,E,F' types
)
a lateral view explode(split(types,",")) col as type ;

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值