HIVE Pivot and Sum

心已入冬 提交于 2019-12-02 02:21:27

Use case and sum():

select own, sum(case when pet='dog' then qty end) as dog,
            sum(case when pet='cat' then qty end) as cat,
            sum(case when pet='cow' then qty end) as cow
  from your_table
 group by own;

For dynamic data you can use MAP

select      own
           ,str_to_map(concat_ws(',',collect_list(concat(pet,':',cast(qty as string))))) as pet_qty

from       (select      own,pet
                       ,sum(qty) qty 

            from        mytable

            group by    own,pet
            ) t

group by    own
;

+-----+---------------------------------+
| own |             pet_qty             |
+-----+---------------------------------+
| bob | {"cat":"1","dog":"6"}           |
| jon | {"cat":"2","cow":"4","dog":"1"} |
| sam | {"cow":"3","dog":"3"}           |
+-----+---------------------------------+
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!