【问题标题】:How to calculate percentage for each month by process如何按流程计算每个月的百分比
【发布时间】:2021-10-01 20:35:59
【问题描述】:

我有如下表格

Process status     startdate
A        complete  09/12/2020 01:12:00
A        complete  09/12/2020 02:13:00
A        failed    09/12/2020 13:15:00
B        complete  09/12/2020 01:00:00
A        complete  10/15/2020 01:00:00
B        complete  10/16/2020 01:12:00
B        failed    10/16/2020 15:00:00

现在我需要编写 sql 来获取每个进程每个月的完整百分比。以下是预期结果。

Process  MonthYear percentage
A        09/2020    33.33
A        10/2020    100
B        09/2020    100
B        10/2020    50

任何帮助将不胜感激。

【问题讨论】:

  • 请标记您的数据库

标签: sql percentage


【解决方案1】:

提取月份/年份取决于您的数据库,但您可以在 mysql 中执行以下操作:

select Process 
      , extract(month_year from startdate)
      , count(case when status ='completed' then 1 end)*1.00 / count(*) percentage
from tablename
group by Process , extract(month_year from startdate)

【讨论】:

    【解决方案2】:

    您可以使用avg() 来计算百分比。我不知道您使用的是什么数据库,但日期/时间函数高度依赖于数据库。一个典型的方法是:

    select year(startdate), month(startdate), process,
           avg(case when status = 'completed' then 100.0 else 0 end)
    from t
    group by year(startdate), month(startdate), process;
    

    您可能需要根据您正在使用的数据库调整年份/日期提取。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-11-11
      • 2016-05-14
      • 1970-01-01
      • 2021-06-02
      • 1970-01-01
      • 2017-11-12
      • 1970-01-01
      相关资源
      最近更新 更多