[英]mysql calculate percentage in select
我有一个基本的投票系统来收集投票。 制表应采用总票数除以总票数来确定是否达到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 ..任何提示或指向良好指导的链接?
恕我直言,最好的方法是在子查询中获得基本结果,并在外部查询中使用它们进行计算。 请注意,由于您只对两列中的recruit_id = 49631
感兴趣,因此可以将此条件移至where
子句。 它也可能会略微提高查询的性能。 作为另一项改进,您可以使用更直接的count
而不是sum
使用其跳过null
s的质量:
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
基本上,您只需要将原始查询作为子查询来完成此操作:
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.