当前位置:   article > 正文

Hive collect_set()、collect_list()列转行,并对转换后的行值排序_hive collect_set排序

hive collect_set排序

Hive collect_set()、collect_list()列转行,和concat_ws()使用,并对转换后的行值排序

1、需求描述

对列值分组,并按一定顺序排序,最后多行合并一行,合并值左到右逆序排列。

2、考点:

  • sort_array(e: column, asc: boolean)将array中元素排序(自然排序),默认asc为true,即默认排升序
  • collect_set() 和 collect_list()的区别是前者去重,后者不去重

3.1、直接上collect_list()代码实现:

  1. select st_name
  2. ,concat_ws(",",sort_array(collect_list(class),false))
  3. ,concat_ws(",",sort_array(collect_list(class),true))
  4. ,concat_ws(",",sort_array(collect_list(class)))
  5. from
  6. (
  7. select "jack" as st_name, '3' as class
  8. union all
  9. select "jack" as st_name, '1' as class
  10. union all
  11. select "jack" as st_name, '2' as class
  12. union all
  13. select "jack" as st_name, '3' as class
  14. union all
  15. select "jack" as st_name, '5' as class
  16. )tb_mid
  17. group by st_name;

结果如下:

st_name concat_ws(,, sort_array(collect_list(class), false))    concat_ws(,, sort_array(collect_list(class), true))     concat_ws(,, sort_array(collect_list(class), true))
jack    5,3,3,2,1       1,2,3,3,5       1,2,3,3,5
Time taken: 0.16 seconds, Fetched 1 row(s)

3.2、直接上collect_set()代码实现:

  1. select st_name
  2. ,concat_ws(",",sort_array(collect_set(class),false))
  3. ,concat_ws(",",sort_array(collect_set(class),true))
  4. ,concat_ws(",",sort_array(collect_set(class)))
  5. from
  6. (
  7. select "jack" as st_name, '3' as class
  8. union all
  9. select "jack" as st_name, '1' as class
  10. union all
  11. select "jack" as st_name, '2' as class
  12. union all
  13. select "jack" as st_name, '3' as class
  14. union all
  15. select "jack" as st_name, '5' as class
  16. )tb_mid
  17. group by st_name;

结果如下:


st_name concat_ws(,, sort_array(collect_set(class), false))     concat_ws(,, sort_array(collect_set(class), true))      concat_ws(,, sort_array(collect_set(class), true))
jack    5,3,2,1 1,2,3,5 1,2,3,5
Time taken: 0.152 seconds, Fetched 1 row(s)

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

闽ICP备14008679号