当前位置:   article > 正文

hive中行转列,列转行的各种情况及解决方法_hive 行转列几种方法

hive 行转列几种方法

1、多行行转列和列转行

行转列:一般用case when,再做一个group by 去掉0值。

列转行:union all

例如:

nameyearsa
xiaohong20001000
dahei20012000
dahei20001000
dahei20012000

转为

nameyear1year2
xiaohong10002000
dahei10002000
  1. select name,
  2. sum(case year when '2001' then sa else 0 end) year1,
  3. sum(case year when '2002' then sa else 0 end) year2,
  4. from a group by name;

反过来则为

  1. select name,'2000' as year,year1 as sa from a
  2. union all
  3. select name,'2001' as year,year2 as sa from a

2、多行转一列,concat_ws,结合collect_set|collect_list

将第一张表转为下表

namedetail
dahei2000:1000,2001:2000
  1. select name,
  2. concat_ws(',',collect_set(concat(year,':',cast(sa as string)))) as detail
  3. from a group by name;

3、一列转多列,如把上表分开,可用split,substring等字符串处理函数。

4、一行转多行,lateral view 子窗口结合 explode

如将上表转换成

namedetail
dahei2000:1000
dahei2001:2000
select name,detail from a lateral view explode(split(detail,'\\,')) a as detail;

如果应用多行 lateral view explode则做笛卡尔积。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/爱喝兽奶帝天荒/article/detail/742667?site
推荐阅读
相关标签
  

闽ICP备14008679号