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
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With