【问题标题】:How to calculate percentage in group by with condition?如何根据条件计算分组百分比?
【发布时间】:2020-05-14 08:32:36
【问题描述】:

我有一个具有此架构的表:

+---------+-------------+-----------+---------+
|   id    |   provider  |  status   | message |
+---------------------------------------------+
|    1    |   Google    |  success  |  ...    |
|    2    |   Facebook  |  failure  |  ...    |
|    3    |   Facebook  |  failure  |  ...    |
|    4    |   Google    |  failure  |  ...    |
+---------------------------------------------+

我需要知道failure 的百分比,例如:

google -> 50% 失败

Facebook -> 100% 失败

我使用 mysql 5.7

我尝试使用 group by 到达此目的地,但我无法

【问题讨论】:

    标签: mysql sql group-by count average


    【解决方案1】:

    您可以进行条件聚合。我喜欢用avg() 来做这个:

    select provider, avg(status = 'failure') failure_ratio
    from mytable
    group by provider
    

    对于每个provider,这会为您提供一个介于01 之间的数值,它表示'failure' status 中记录的比率。如果您想要一个百分比,可以将其乘以 100

    【讨论】:

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