如何通过sql显示轮询结果

时间:2016-04-29 16:08:14

标签: mysql sql select

我有一个useriInterface,我在其中捕获单选按钮点击并根据所选值增加数据库中的计数器。

这一切都很好。

我的问题是如何显示轮询结果百分比值?

这是我的数据库结构

CREATE TABLE `poll_results` (
  `name` varchar(50) DEFAULT NULL,
  `count` int(11) DEFAULT NULL,
  `modified_date` varchar(50) DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;



Insert into poll_results (name,count,modified_date)values ('pollchoiceone' , 3 , now());
Insert into poll_results (name,count,modified_date)values ('pollchoicetwo' , 10 , now());
Insert into poll_results (name,count,modified_date)values ('pollchoicethree' , 7 , now());
Insert into poll_results (name,count,modified_date)values ('pollchoicefour' , 0 , now());

是否可以通过选择查询实现这一目标?

http://sqlfiddle.com/#!9/e5e835/1

2 个答案:

答案 0 :(得分:2)

你可以cross join从你的表中查询一个查询,该查询将整个投票数相加,然后除以两个。 E.g:

SELECT     name, `count`, `count` / `total_count` * 100 AS percetnage
FROM       poll_results
CROSS JOIN (SELECT SUM(`count`) AS `total_count` 
            FROM   poll_results) t

<强> SQLFiddle example

答案 1 :(得分:1)

使用预先构建的total_count表的替代解决方案:

SELECT name, `count`, `count`/t.total_count * 100 AS percentage
FROM poll_results, (select sum(`count`) AS total_count from poll_results) t

SQL Fiddle