相关查询以获取sql oracle中的开始序列和结束序列

时间:2018-11-06 19:34:45

标签: sql oracle

我有一张这样的桌子:

employee type seq
A        loa  1
A        loa  2
A        rfl  3
A        loa  4
A        rfl  5
A        loa  6
A        loa  7
A        rfl  8

现在我想要一个表,该表为我提供所有开始和结束序列。开始序列只是该行的当前序列。结束序列是sequence,是该序列之后的第一个rfl。因此,对于我的示例,结果必须是:

employee type beginSeq endSeq
A        loa  1        3
A        loa  2        3
A        loa  4        5
A        loa  6        8
A        loa  7        8

我想做两张桌子。 表格loa =

select * from table where type='loa'

和表格rfl =

    select * from table where type='rfl'

然后我只是想我可以做到:

select loa.* from loa
    left join (select min(seq) from rfl where rfl.seq>=loa.seq)
    on rfl.employee = loa.employee

,但是不幸的是,此时子查询中的loa.seq尚不清楚。 有人建议吗?

2 个答案:

答案 0 :(得分:3)

您可以将相关子查询用作:

select t.*,
       ( select min(seq) from tab where type = 'rfl' and seq > t.seq )
       as endSeq
  from tab t
 where t.type = 'loa'
 order by t.seq;

Rextester Demo

答案 1 :(得分:3)

在Oracle中,我将使用lead()

select *
from (select loa.*,
             lead(case when type = 'rfl' then seq end ignore nulls) over (partition by employee order by seq) as end_seq
      from loa
     ) loa
where type = 'loa';

ignore null拉下一个非null的值。 case语句仅在寻找'rfl'值。

您也可以这样表示:

select *
from (select loa.*,
             min(case when type = 'rfl' then seq end) over (partition by employee order by seq rows between current row and unbounded following) as end_seq
      from loa
     ) loa
 where type = 'loa';