使用PHP / Mysql计算民意调查的百分比

时间:2017-01-07 16:24:09

标签: php mysql algorithm

我正在研究民意调查系统,我想计算这个变种被选中的时间百分比   例如,我有4个可用的变种

Poll name | Vote number  
  Java    |     250
  Python  |     200
  C#      |      90
  PHP     |      1

我的Polls db Id,Tex,Creator_id中有3列 Poll_variants我的问题数据库中有4列是

Id | Poll_id | Variant | Vote_num
1  |    1    |  Java   | 250 
1  |    1    |  Python | 200 
1  |    1    |  C#     | 90 
1  |    1    |  PHP    | 1 

2 个答案:

答案 0 :(得分:1)

查找子查询中每个poll_id的总投票数,并将其与主表连接,以查找每个变量的百分比。

select t1.*, 100 * t1.votes/t2.total_votes percentage
from Poll_variants t1
inner join (
  select poll_id, sum(votes) total_votes
  from Poll_variants
  group by poll_id
) t2 on t1.poll_id = t2.poll_id;

答案 1 :(得分:0)

您可以使用以下SQL

SELECT *,Votes*100/(SELECT sum(Votes) from Poll_variants)total FROM Poll_variants WHERE 1