【问题标题】:计算 MySQL 查询的百分比
【发布时间】:2022-01-23 15:56:50
【问题描述】:

我有一个查询,它返回一些数据计数如下,基本上这个表是posts 并且将包含inboundoutbound 帖子。我想做一个查询,返回出站帖子的百分比。

例如

select count(*) as total, 
(select count(*) from posts where inbound = 0 and accountid = 333) as inbound,
(select count(*) from posts where inbound = 1 and accountid = 333) as outbound 
from account a
    join posts p on p.accountId = a.id where a.id = 333 
group by a.id;

这将返回类似以下内容...

+-------+---------+----------+
| total | inbound | outbound |
+-------+---------+----------+
|   802 |     525 |      277 |
+-------+---------+----------+

如何修改上面的查询,使其返回一个额外的列来计算总数的出站百分比,例如(277 / 802) * 100 例如(outbound / total) * 100)

那么结果中带有新列的预期输出将如下四舍五入到最接近的整数?

+-------+---------+----------+---------------------+
| total | inbound | outbound |  outboundPercentage |
+-------+---------+----------+---------------------+
|   802 |     525 |      277 |                  35 |
+-------+---------+----------+---------------------|

【问题讨论】:

    标签: mysql sql


    【解决方案1】:

    我认为你可以使用最简单的方法:

    with counts as (
      select 
        count(*) as total,
        count(nullif(inbound, 0)) as inbound,
        count(nullif(inbound, 1)) as outbound
      from posts
      where accountid = 333
    ) select 
        * ,
        round((outbound / total) * 100) outboundPercentage
    from counts;  
    

    MySQL 8.0 fiddle

    【讨论】:

    • super @Slave 正是我想很快接受的东西:)
    【解决方案2】:

    您可以简单地计算 sub queryjoin 与帐户的子查询中的帖子总数、入站总数、出站总数和百分比。

    SELECT p.total,
           p.outbound,
           p.inbound,
           p.outboundPercentage
    FROM `account` AS a
    JOIN
      (SELECT accountid,
              COUNT(`id`) AS total,
              SUM(IF(inbound=1
                     AND accountid=333, 1, 0)) AS outbound,
              SUM(IF(inbound=0
                     AND accountid=333, 1, 0)) AS inbound,
              ROUND(((SUM(IF(inbound=1
                             AND accountid=333, 1, 0)) / COUNT(`id`)) * 100), 2) AS outboundPercentage
       FROM posts
       GROUP BY accountid) AS p ON p.accountid = a.id
    WHERE a.id = 333
    GROUP BY a.id
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-04-06
      • 2012-05-01
      • 2013-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多