我有下表,里面有员工处理的文档信息,你可以看到不同的员工可以全天处理同一个文档。 我需要获取员工开始处理文档的开始日期/时间,但问题是有时他们不会开始处理文档,直到他们在系统上单击开始,即 process_type 获得值 1,但是当其他员工没有处理文档时,我还需要这些信息(在 process_type 上没有价值)。
主桌
期望的结果将如本表所示(行 = 1 是事件的开始)
想要的结果
我尝试过使用 row_number,而不是 partition_by,甚至使用 WHERE 子句或 CASE WHEN,但是当名称更改为另一名员工时,它会一直给出 row = 1 ...
标准间隙和孤岛方法用于描绘计数器重置的块。假设(最多)只有一行的进程类型为 1,在第二步中,我们只需要获取该特定行号来计算将跟随它的行的相对偏移量。如果不存在这样的值,则回退将使用该块中的第一个行号作为计数的起点。调整后的输出行号然后从这些值派生:
with grouped as (
select *,
row_number() over (
partition by document_id
order by
last_modification,
case when process_type is null then 0 else 1 end,
employee) as rn0,
row_number() over (
partition by document_id, employee
order by
last_modification,
case when process_type is null then 0 else 1 end) as rn
from T
), tagged as (
select *,
min(case when process_type = 1 then rn end) over (
partition by document_id, employee, rn0 - rn) as ofs,
min(rn) over (
partition by document_id, employee, rn0 - rn) as ofs2
from grouped
)
select document_id, employee, last_modification, process_type,
case when rn < ofs then 0
when ofs is not null then rn - ofs + 1
else rn - ofs2 + 1 end as "row"
from tagged
order by document_id, rn0, employee;
对我来说很好用:https://dbfiddle.uk/Ot9wfM0W
上面的示例数据前六行都有相同的时间戳。如表所示,Emma 排在最后。 (也许那只是因为时间被按分钟截断了?)如果这不是一个错误,那么您将需要定义一个规则来处理这种情况。我的规则是按员工排序,这基本上是任意的。在我的小提琴中,我调整了时间顺序以避免重叠时间。