数据库
首页 > 数据库> > MySQL中选择百分比计算

MySQL中选择百分比计算

作者:互联网

我有一个收集选票的基本投票系统.列表应采用“赞成”总数除以“总数”,以确定是否达到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.

解决方法:

最简单的方法,恕我直言,是将基本结果放在子查询中,并在外部查询中使用它们进行计算.请注意,由于您只对这两列中的hire_id = 49631感兴趣,因此可以将此条件移至where子句.它还可能会稍微改善查询的性能.作为另一个改进,您可以使用更直接的计数,而不是通过跳过空值的质量求和:

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,percentage,sql,mysql
来源: https://codeday.me/bug/20191027/1941002.html