Skip to content
Advertisement

Calculating Value Count and Percentage

I have a table Currently Enrolled

The table is basically to get an idea of how many supporters, undecided, and opposition they were. Then once I get the count I wanted to then do another calculation to find out what that percentage was.

Essentially what I want to be able to do is:

  1. Count the total number of supporters:
    SELECT count(*) AS ‘SUPPORTERS’ FROM CURRENTLY ENROLLED WHERE status = ‘Supporter’ results were 13

  2. Count the total number of opposition:
    SELECT count(*) AS ‘OPPOSITION’ FROM CURRENTLY ENROLLED WHERE value = ‘Opposition’ results were 11

  3. Count the total number of undecided persons using a similar statement:
    SELECT count(*) AS ‘UNDECIDED’ FROM CURRENTLY ENROLLED WHERE value = ‘Undecided’ results were 5

So with the count, I can see that they’re 29 total individuals. I wanted to be able to get the percentage of each of them separately. Something like
13/29 * 100 = 44%
11/29 * 100 = 37%
5/29 * 100 = 17%

However, I am lost on how to write this query.

Hope I am making this clear as to the intentions.

Advertisement

Answer

Use a CTE for the total and group by status for the percentage:

with cte as (select count(*) as cnt from `currently enrolled`)
select status, sum(100)/cnt
from `currently enrolled`, cte
group by 1
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement