简体   繁体   中英

Total and aggregate percentage in hive

I have a table like

fruit   sold
----------------
apple   5
apple   10
apple   3
orange  2
orange  5

I wanna get the total and also aggregate percentage. So the output would be

fruit   sold
----------------
All     25
apple   52%
orange  48%

As of all sold apple is 13/25 and orange is 12/25.

I think that's union all between a query that generates the total sum, and another that computes the total per fruit:

select 'All' as fruit, sum(sold) sold from mytable
union all
select fruit, 100.0 * sum(sold) / sum(sum(sold)) over()
from mytable
group by fruit

One thing to be careful about is that the datatypes of the subqueries need to be aligned. This puts everything as numbers (both the total sales, and the percentages per fruit).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM