mysql 计算 select 中的百分比

mysql calculate percentage in select

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

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;

这个returns

+-------------+-----------+
| 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。有什么提示或好的指导链接吗?

基本上,您只需将原始查询设为子查询即可:

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;

稍微取决于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;

恕我直言,最简洁的方法是在子查询中获得基本结果,然后在外部查询中使用它们进行计算。请注意,由于您只对两列中的 recruit_id = 49631 感兴趣,因此可以将此条件移至 where 子句。它还可能会略微提高查询的性能。作为另一项改进,您可以使用更直接的 count 而不是 sum,方法是使用其跳过 nulls:

的质量
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