繁体   English   中英

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

[英]Get percent result from database poll choices

我对自己的网站进行了简单调查,发现问题有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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM