php - 从数据库轮询选择中获取百分比结果

标签 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% ......等等。

最佳答案

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

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;

关于php - 从数据库轮询选择中获取百分比结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21759394/

相关文章:

PHP MySQL 调用过程并继续

php - 检查IP地址是否存储在数据库中

php - 网站到 POS 打印机

javascript - Jquery `.find()` 找不到 `document` `input` 其值=

mysql - 服务器端渲染/模板

php - 将单词分为两部分 : letters and numbers

jQuery 选择器效率

javascript - 在变暗的页面上显示模态 DIV

mysql - 创建表时 UNIQUE KEY 语法错误

mysql - 升级 Bugzilla 获取错误表已存在