获取数据库轮询选择的百分比结果

时间:2014-02-13 16:07:10

标签: php jquery mysql count percentage

我为我的网站做了一个简单的调查,问题有3-5个或更多选择(单选按钮或复选框)。

在php中,我通过代码获得了选择某个选择的号码:

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

这是针对问题13(q13)和第三个选择(a3)。

我需要知道如何计算问题的任何给定答案的数量(例如q13:a1 + a2 + a3 + a4),可能就像1600选择所有答案一样,而不是上面的代码可以得到每个选项的答案数,我从整个问题的总答案中得到百分比。

所以它告诉我,回答问题13的人中有15%选择了答案3,而答案4则选择了55%......等等。

1 个答案:

答案 0 :(得分:0)

首先,您可以使用聚合获取计数:

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

我猜测count(distinct)确实没有必要。最好尽可能使用count()

要获得总数,请加入:

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;

您可以使用以下内容获得百分比:

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;
相关问题