【问题标题】:mysql calculate percentage in selectmysql在select中计算百分比
【发布时间】:2016-09-26 03:32:41
【问题描述】:

我有一个收集选票的基本投票系统。制表应以总赞成票除以总票数来确定是否达到 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。有任何提示或指向良好指导的链接吗?

【问题讨论】:

    标签: mysql sql select percentage


    【解决方案1】:

    恕我直言,最简洁的方法是将基本结果放在子查询中,并在外部查询中使用它们进行计算。请注意,由于您只对两列中的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
    

    【讨论】:

    • 将其直接粘贴到'FROM votes WHERE recruit_id = 49631) t' 中,我将其修改为 t;以同样的结果结束。我还在玩代码,试图弄清楚发生了什么。感谢您提供有关使用计数忽略空值的提示,它确实加快了我的查询时间!
    • 我这样做了,我需要向表中添加更多数据以确保它按预期工作,但谢谢! select sum(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) as t;
    【解决方案2】:

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

    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;
    

    【讨论】:

      【解决方案3】:

      根据 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;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-03-22
        • 1970-01-01
        • 1970-01-01
        • 2013-11-15
        • 2022-01-23
        • 2012-09-20
        • 2012-04-05
        相关资源
        最近更新 更多