case when then else end 行转列/列转行
发布日期:2022-02-27 02:38:01 浏览次数:45 分类:技术文章

本文共 1716 字,大约阅读时间需要 5 分钟。

- 行转列(多行转单列)

-- 数据表 row2col_1:col1    col2    col3a       b       1a       b       2a       b       3c       d       4c       d       5c       d       6-- 将其转化为:col1    col2    col3a       b       1,2,3c       d       4,5,6
  • 一般使用group by column…+concat_ws+collect_list/collect_set来实现
concat_ws( ‘,’ , collect_list(column))-- 备注:collect_list不去重,collect_set去重。a)concat_ws(参数1,参数2),用于进行字符的拼接 	参数1—指定分隔符 	参数2—拼接的内容 b)collect_set(col3),它的主要作用是将某字段的值进行去重汇总,产生array类型字段-- column的数据类型是String 如果需要转换为string就使用concat_ws( ‘,’ , collect_list(column as string))
创建表:create table row2col_1(col1 string,col2 string,col3 int)row format delimitedfields terminated by ',';加载数据:load data local inpath '/root/hivedata/row2col_1.txt' into table row2col_1;a,b,1a,b,2a,b,3c,d,4c,d,5c,d,6
-- 执行代码select col1, col2, concat_ws('|', collect_set(cast(col3 as string))) as col3from row2col_1group by col1, col2;

- 列转行(针对单列变多行)

数据表 col2row_2:col1    col2    col3a       b       1,2,3c       d       4,5,6现要将其转化为:col1    col2    col3a       b       1a       b       2a       b       3c       d       4c       d       5c       d       6
lateral view explode( split ( order_value , ‘ , ‘ )-- 使用lateral view结合explode这样的UDTF进行实现,由于explode的参数要求是list()或者array()类型,所以往往还需要用到spilt函数进行分割。
-- 创建表:create table col2row_2(col1 string,col2 string,col3 Array
)row format delimitedfields terminated by '\t'collection items terminated by ',';create table col2row_2(col1 string,col2 string,col3 string)row format delimitedfields terminated by '\t';--加载数据:load data local inpath '/root/hivedata/col2row_2.txt' into table col2row_2;a b 1,2,3c d 4,5,6
-- 执行语句select col1, col2, lv.col3 as col3from col2row_2 lateral view explode(split(col3, ',')) lv as col3;

转载地址:https://blog.csdn.net/weixin_43401381/article/details/104531848 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:四 Nifi 处理器 初体验以及常用组件说明
下一篇:Spark数据倾斜的调优

发表评论

最新留言

哈哈,博客排版真的漂亮呢~
[***.90.31.176]2024年04月02日 02时08分30秒