如何在列中获得四个连续的空值

时间:2014-06-09 15:57:10

标签: sql oracle oracle11g null

有:

create table theater(seatno varchar2(3),status varchar(1));

insert into theater('A1','');
insert into theater('A2','B');
insert into theater('A3','B');
insert into theater('A4','');
insert into theater('A5','');
insert into theater('A6','');
insert into theater('A7','');

我的要求是获得四个连续的座位号,其中状态为空 A4,A5,A6,A7

我尝试过Lead,Lag功能但没有成功。

3 个答案:

答案 0 :(得分:3)

第一步,在状态中只获得null(平凡):

select * from  theater
where status is null

现在我们将座位分组为连续组:

select seat - row_number() over (order by seat) grp, seat
where status is null

这将为连续的座位组提供相同的组,例如

grp   seat
---   ----
0     1
0     2
1     4
1     5

然后在一组中你要求下一个第4个元素

select lead(seat, 4) over (partition by grp), grp, seat from (
previous query
)

作为最后一步,您过滤第4个元素不为空。 这将是你的答案。

答案 1 :(得分:0)

这样的事情应该会有所帮助。

select t1.seatno
, t2.seatno
, t3.seatno
, t4.seatno

from theatre t1 join theatre t2 on t2.seatno = t1.seatno + 1
join theatre t3 on t3.seatno = t2.seatno + 1
join theatre t4 on t4.seatno = t3.seatno + 1

where t1.status is null
and t2.status is null
and t3.status is null
and t4.status is null

答案 2 :(得分:-1)

我会使用派生表添加row_seatno和col_seatno列,然后使用listagg函数创建整行状态的聚合列表。

接下来,我会连续找到4个NULLS的实例,这个实例有这个子串,&n; N; N; N; N',如下所示:

        select seatno
  ||', '
  || mod3_t.row_seatno
  || to_char( to_number(mod3_t.col_seatno) + 1)
  || ', '
  || mod3_t.row_seatno
  || to_char( to_number(mod3_t.col_seatno) + 2)
  || ', '
  || mod3_t.row_seatno
  || to_char(to_number(mod3_t.col_seatno) + 3)
from
  (select mod2_t.seatno,
    mod2_t.row_seatno,
    mod2_t.col_seatno,
    instr(mod2_t.row_status, 'N;N;N;N', to_number(mod2_t.col_seatno) ,1) cont_null
  from
    (select mod1_t.seatno,
      mod1_t.row_seatno,
      mod1_t.col_seatno,
      listagg(nvl(mod1_t.status,'N'), ';') within group (
    order by mod1_t.col_seatno) over (partition by mod1_t.row_seatno ) row_status
    from
      (select regexp_substr( t.seatno, '[[:upper:]]+',1,1) row_seatno,
        regexp_substr( t.seatno, '[[:digit:]]+',1,1) col_seatno,
        seatno,
        status
      from theater t
      ) mod1_t
    ) mod2_t
  where cont_null =1
  ) mod3_t