Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL - Calculate percentage on count(column)

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
like image 369
Dean Flaherty Avatar asked May 18 '16 15:05

Dean Flaherty


People also ask

What is the formula to count percentage?

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%.

How do I calculate percentage of total in MySQL?

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.

How do you calculate running percentage in SQL?

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.


2 Answers

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.

like image 110
Gordon Linoff Avatar answered Oct 21 '22 12:10

Gordon Linoff


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
like image 23
juergen d Avatar answered Oct 21 '22 13:10

juergen d