HIVE Pivot and Sum

后端 未结 2 638
北荒
北荒 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"}           |
    +-----+---------------------------------+
    
    0 讨论(0)
  • 2021-01-06 06:56

    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;
    
    0 讨论(0)
提交回复
热议问题