mysql在select中计算百分比

时间:2016-05-27 17:44:01

标签: mysql sql select percentage

我有一个收集选票的基本投票系统。制表应采用总票数除以总票数来确定是否达到2/3多数。 目前,我可以使用此查询返回数据

select sum(case when vote is not null and recruit_id=49631 then 1 else 0 end) 
as total_votes, 
sum(case when vote=1 and recruit_id=49631 then 1 else 0 end) as total_yes from votes;

返回

+-------------+-----------+
| total_votes | total_yes |
+-------------+-----------+
|           3 |         2 |
+-------------+-----------+

我想做的是这样的事情

+-------------+-----------+-----------+
| total_votes | total_yes | YESPercent|
+-------------+-----------+-----------+
|           3 |         2 |      66.6 |
+-------------+-----------+-----------+

我尝试使用类似的东西:

select sum(case when vote is not null and recruit_id=49631 then 1 else 0 end) as total_votes, 
sum(case when vote=1 and recruit_id=49631 then 1 else 0 end) as total_yes,
sum(total_votes,total_yes,(total_yes/total_votes)*100) as YESPercent from votes;

它不会识别最终部分的total_yes或total_votes ..任何提示或指向良好指导的链接?

3 个答案:

答案 0 :(得分:2)

执行此操作的最佳方法是IMHO,它将在子查询中获得基本结果,并在外部查询中使用它们进行计算。请注意,由于您只对两列中的recruit_id = 49631感兴趣,因此可以将此条件移至where子句。它也可能会略微提高查询的性能。作为另一项改进,您可以通过使用其跳过count s的质量来使用更直接的sum代替null

SELECT total_votes, total_yes, total_yes * 100 / total_votes AS yes_percent
FROM   (SELECT COUNT(vote) AS total_votes, 
               COUNT(CASE WHEN vote = 1 THEN 1 END) as total_yes,
         FROM  votes
         WHERE recruit_id = 49631) t

答案 1 :(得分:1)

基本上,您只需要将原始查询作为子查询来完成此任务:

SELECT total_votes, total_yes, sum(total_votes,total_yes,(total_yes/total_votes)*100) as YESPercent
FROM
(select 
sum(case when vote is not null and recruit_id=49631 then 1 else 0 end) as total_votes, 
sum(case when vote=1 and recruit_id=49631 then 1 else 0 end) as total_yes
from votes) as v;

答案 2 :(得分:1)

稍微依赖于SQL方言,别名可以重复使用或不重用。在mysql中,你受此限制。解决方案是子查询:

SELECT total_votes,total_yes,sum(total_votes,total_yes,
(total_yes/total_votes)*100) as YESPercent 
FROM (
  select sum(case when vote is not null and recruit_id=49631 then 1 else 0 end) as total_votes, 
  sum(case when vote=1 and recruit_id=49631 then 1 else 0 end) as total_yes,
  sum(total_votes,total_yes,(total_yes/total_votes)*100) as YESPercent
  from votes) a;