HIVE Pivot and Sum

后端 未结 2 642
北荒
北荒 2021-01-06 06:09

I have a table that I am trying to figure out how to pivot and sum based on the values in a second column.

Example input:

|own|pet|qty|
|---|---|---|         


        
2条回答
  •  轮回少年
    2021-01-06 06:49

    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"}           |
    +-----+---------------------------------+
    

提交回复
热议问题