Oracle - 沿间隔对值进行分组

Oracle - grouping values along interval

我需要查询一个 table,包含一个步骤 ID + 值。 结果将列出间隔及其相关值。 这里的区间定义为"succession of contiguous ids of steps, sharing same data value".

我很难用语言来描述它,所以请看这个:

由此table

  Step ! Data
  ------------
   1   !  A
   2   !  A
   3   !  A
   5   !  A
   6   !  B
  10   !  A

我需要以下报告

  From ! To   ! Data
  -------------------
     1 !   3  !   A
     5 !   5  !   A
     6 ! null !   B
    10 ! null !   A

我以为 lead() 会帮我解决这个问题,但没有成功。

您可以生成一个数字序列并从 step 中减去。当值是连续的时,这将是一个常量:

select min(step) as from_step, max(step) as to_step, data
from (select t.*,
            row_number() over (partition by data order by step) as seqnum
     from t
    ) t
group by (step - seqnum), data;

编辑:

不太清楚 NULL 的来源。如果我推测它们是每个值的最后一个值,你可以这样做:

select min(step) as from_step,
       (case when max(step) <> max_step then max(step) end) as to_step,
       data
from (select t.*,
             max(step) over (partition by data) as max_step
             row_number() over (partition by data order by step) as seqnum
     from t
    ) t
group by (step - seqnum), data, max_step;
select      min (step)                                                   as "from"
           ,nullif (max (step),max(min(step)) over (partition by data))  as "to"
           ,data

from       (select      step,data
                       ,row_number () over (partition by data order by step) as n

            from        t
            ) 

group by    data
           ,step - n            

order by    "from"