Question

I made a simple survey for my website with questions having 3-5 or more choices (radio buttons or check boxes).

In php, I get the number who chose a certain choice through the code:

  $query = "select count(distinct id) from survey_ans where question='q13' and answer='a3';";
  $res = mysql_query($query, $connection);
  $row = mysql_fetch_array($res);

this is for question 13 (q13), and the third choice (a3).

What I need is to know how can I count the numbers of any given answers for a question (e.g. q13: a1 +a2 + a3 + a4), the could be like 1600 who chose all the answers altogether, and instead of the above code to get the number of answers for each choice, I get the percentage from the total answers of the whole question.

So it shows me that 15% of the people who answered question 13 chose answer 3, while answer 4 got 55%.. etc.

Was it helpful?

Solution

First, you can get the counts using aggregation:

select answer, count(id)
from survey_ans
where question = 'q13'
group by answer;

I am guessing that the count(distinct) really isn't necessary. count() is better to use when you can.

To get the total, join that in:

select sa.answer, count(sa.id), tot.total
from survey_ans sa cross join
     (select count(*) as total from survey_ans where question = 'q13') as tot
where question = 'q13'
group by sa.answer;

You can get the percentage with something like:

select sa.answer, 100.0*count(sa.id)/tot.total as percentage
from survey_ans sa cross join
     (select count(*) as total from survey_ans where question = 'q13') as tot
where question = 'q13'
group by sa.answer;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top