hive中的行列转换问题(知识点+案例解析)

一.多行转单列
1.涉及到的函数

  • List item

    数据收集函数
    collect_set:把多行数据收集为一行,返回set集合,去重无序
    collect_list: 把多行数据收集为一行,返回list集合,不去重有序
    字符串拼接函数
    concat: 直接拼接字符串
    concat_ws: 指定分隔符拼接
    举例:
    select concat(‘a’,‘b’,‘c’)
    select concat_ws(‘,’,‘a’,‘b’)

2.案例
–原表
±---------------±---------------±---------------±-+
| word1 |word2 | num |
±---------------±---------------±---------------±-+
| a | b | 1 |
| a | b | 2 |
| a | b | 3 |
| c | d | 4 |
| c | d | 5 |
| c | d | 6 |
±---------------±---------------±---------------±-+

–目标表
±------±------±-------±-+
| word1 | word2 | num |
±------±------±-------±-+
| a | b | 1-2-3 |
| c | d | 4-5-6 |
±------±------±-------±-+

  • – 建表

create table table2(
word1 string,
word2 string,
num string
)
row format delimited fields terminated by ‘\t’
collection items terminated by ‘,’;

  • – 导入数据

load data local inpath ‘/data/test1.txt’ into table table2;
truncate table table2;
select * from table2;

  • – 多行转单列 数据处理

select word1,word2,
concat_ws(‘,’,collect_list(num)) as num
from table2
group by word1,word2;

二.单列转多行

  • 1.涉及到的函数

explode + later view
2.案例
–原表
±------±------±-------±-+
| zimu1 | zimu2 | shuzi |
±------±------±-------±-+
| a | b | 1,2,3 |
| c | d | 4,5,6 |
±------±------±-------±-+

–目标表
±---------------±---------------±---------------±-+
| zimu1 | zimu2 | shuzi |
±---------------±---------------±---------------±-+
| a | b | 1 |
| a | b | 2 |
| a | b | 3 |
| c | d | 4 |
| c | d | 5 |
| c | d | 6 |
±---------------±---------------±---------------±-+

  • – 建表

create table table1(
zimu1 string,
zimu2 string,
shuzi string
)
row format delimited fields terminated by ‘\t’
collection items terminated by ‘,’;

  • – 导入数据

load data local inpath “/data/test.txt” into table table1;
truncate table test.table1;
select * from table1;

  • –数据处理
  • List item

select
w.zimu1,w.zimu2,
r.shuzi
from table1 w
lateral view explode(split(w.shuzi,‘,’)) r as shuzi;

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

lucky bigdata

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值