Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I find percentages of a column using Hive/Presto

Tags:

hive

presto

Let's say I have a table that looks like:

Reason          | Duration
Eating              40
Drinking            60
Everything Else     100

How do I get a table like this:

Reason          | Duration | Duration Percent
Eating              40             20
Drinking            60             30
Everything Else     100            50
like image 573
UtsavShah Avatar asked Jun 11 '17 00:06

UtsavShah


People also ask

How is percentage calculated in hive?

Use below query to calculate the percentage: SELECT roll_no,CAST(subject1+subject2+subject3+subject4+subject5+subject6 AS float)/6.0 AS percentage FROM bdp.

How do I find the percentage of a column in SQL?

Finding Percentages between two columns is straightforward. You can simply use the column names and the division operator “/” to divide values in one column by another. The result is a list of values that correspond to the result of the division of all the values in the two columns.


1 Answers

You can use a window function to compute the total:

SELECT reason, duration, (duration * 100.0) / sum(duration) OVER () pct
FROM (
  VALUES
    ('eating', 40),
    ('drinking', 60),
    ('other', 100)
) AS t (reason, duration)

Note that Presto (per the SQL standard) performs integer division, so it is necessary to convert one of the values to a double or decimal (otherwise the result will be zero).

  reason  | duration | pct  
----------+----------+------
 eating   |       40 | 20.0 
 drinking |       60 | 30.0 
 other    |      100 | 50.0 
(3 rows)
like image 164
David Phillips Avatar answered Oct 02 '22 13:10

David Phillips