计算重复状态的迭代

时间:2019-07-08 18:47:03

标签: sql oracle

已更新:

我有一个表,用于记录批准工作流程的状态。该表如下所示:

NUMBER      STATUS          STATUS_DATE             

248033      Registration    2017-12-02 12:20:58.0       
248033      Processed       2017-12-04 11:29:16.0   
248033      Approve         2017-12-04 11:32:11.0   
248033      Approved        2017-12-04 16:27:45.0   
248033      Completed       2017-12-05 06:01:29.0   
248033      Registration    2017-12-07 10:02:16.0   
248033      Approve         2017-12-08 15:48:09.0   
248033      Processed       2017-12-08 16:15:00.0   
248033      Completed       2017-12-09 10:23:32.0   
248033      Registration    2018-07-20 16:49:25.0   
248033      Processed       2018-07-20 16:54:32.0   
248033      Completed       2018-07-25 11:41:59.0   
248033      Registration    2019-03-11 09:56:10.0   
248033      Processed       2019-03-11 09:56:11.0   
248033      Completed       2019-03-12 06:01:10.0   

我想计算一个文档被批准的次数(迭代/周期)。迭代始终以“ REGISTRATION”开始,以“ COMPLETED”结束。但是在这两种状态之间,可能会看到许多状态之间来回“翻转”。同样,“已处理”,“批准”或“已批准”也可以省略。

我想按以下方式对批准迭代进行分组:

NUMBER      STATUS          STATUS_DATE             ITERATION

248033      Registration    2017-12-02 12:20:58.0       1   
248033      Processed       2017-12-04 11:29:16.0       1
248033      Approve         2017-12-04 11:32:11.0       1
248033      Approved        2017-12-04 16:27:45.0       1
248033      Completed       2017-12-05 06:01:29.0       1
248033      Registration    2017-12-07 10:02:16.0       2
248033      Approve         2017-12-08 15:48:09.0       2
248033      Processed       2017-12-08 16:15:00.0       2
248033      Completed       2017-12-09 10:23:32.0       2
248033      Registration    2018-07-20 16:49:25.0       3
248033      Processed       2018-07-20 16:54:32.0       3
248033      Completed       2018-07-25 11:41:59.0       3
248033      Registration    2019-03-11 09:56:10.0       4
248033      Processed       2019-03-11 09:56:11.0       4
248033      Completed       2019-03-12 06:01:10.0       4

关于如何使用Oracle SQL实现此目标的任何想法?

1 个答案:

答案 0 :(得分:1)

使用OVER子句对注册进行计数:

select
  number,
  status,
  status_date,
  count(case when status = 'Registration' then 1 end) over (order by status_date)
    as iteration
from mytable
order by status_date;

编辑:您说“注册”可以在“完成”之前多次发生。您可以改为计算“已完成”,如果行本身不是“已完成”行,则只能加1。

select
  number,
  status,
  status_date,
  count(case when status = 'Completed' then 1 end) over (order by status_date) +
    case when status = 'Completed' then 0 else 1 end as iteration
from mytable
order by status_date;