sqlpercentagecalculated-field

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

Solution

  • If your DB engine 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