I have the following piece of code which counts how many times something appears in the event column.
SELECT event, count(event) as event_count
FROM event_information
group by event
event event_count
a 34
b 256
c 45
d 117
e 3
I want to be able to calculate the percentage of each of the rows like so.
event event_count event_percent
a 34 7.47
b 256 56.26
c 45 9.89
d 117 25.71
e 3 0.66
Percentage can be calculated by dividing the value by the total value, and then multiplying the result by 100. The formula used to calculate percentage is: (value/total value)×100%.
Use the OVER() Function to Calculate Percentage in MySQL The OVER() function is one of the Window Functions in MySQL that computes the values over a certain range of values. We can use this function to calculate percentages as well.
The subquery SELECT SUM(Sales) FROM Total_Sales calculates the sum. We can then divide the running total, "SUM(a2. Sales)", by this sum to obtain the cumulative percent to total for each row.
Most SQL dialects support ANSI standard window functions. So, you can write the query as:
select event, count(*) as event_count,
count(*) * 100.0/ sum(count(*)) over () as event_percent
from event_information
group by event;
Window functions are generally more efficient than subqueries and other methods.
If your DB engines does not support window functions then you can use a subquery:
SELECT event,
count(event) as event_count,
count(event) * 100.0 / (select count(*) from event_information) as event_percent
FROM event_information
group by event
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