当前位置:   article > 正文

hive 列转行与行专列_hive-sql pivot

hive-sql pivot

1. 行转列

1.1 现状

SQL SERVER 2005 提供了行转列方法pivot(),以及列转行unpivot()方法;

但hive 里面没有自带pivot函数,以下为自己实现:

实现将原始表

转为目标表

1.2 简单实现

  1. select name,
  2. sum(if(course='math', score, null)) as math,
  3. sum(if(course='english', score, null)) as english,
  4. sum(if(course='chinese', score, null)) as chinese
  5. from table_name
  6. group by name

1.3 按日期对group by 字段 整合成一行

  1. select a.dt,
  2. cnt1, concat(round(cnt1/total_cnt*100,2), '%') as rate1,
  3. cnt2, concat(round(cnt2/total_cnt*100,2), '%') as rate2
  4. from (
  5. select dt,
  6. sum(if(code='101', cnt, null)) as cnt1,
  7. sum(if(code='102', cnt, null)) as cnt2
  8. from (
  9. select dt, code, count(1) as cnt
  10. from test.table_1
  11. group by dt, code
  12. ) a1
  13. group by dt
  14. ) a
  15. left join (
  16. select dt, count(1) as total_cnt
  17. from test.table_1
  18. group by dt
  19. ) b
  20. on a.dt=b.dt;

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

闽ICP备14008679号