7

I need to query a table, containing a step id + value. The result will list the intervals, along with their associated value. Intervals here are defined as "succession of contiguous ids of steps, sharing same data value".

I'm having a hard time describing it in words, so please see this:

From this table

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

I need the following report

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

I thought lead() would help me out here, but did not succeed.

4

2 回答 2

1

您可以通过生成一系列数字并从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;

编辑:

目前尚不清楚NULLs 来自何处。如果我推测它们是每个值的最后一个值,您可以这样做:

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;
于 2016-12-20T12:55:01.790 回答
1
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"           
于 2016-12-20T13:16:25.523 回答