获取oracle中有序行集的范围

时间:2015-03-05 06:56:21

标签: sql oracle

我有这张桌子。

Seq key 1 A 2 A 3 A 4 A 5 B 6 C 7 C 8 C 9 C 10 A 11 A

我想查询它并按顺序返回一系列键。

key strt end A 1 4 B 5 5 C 6 9 A 10 11

我尝试按键分组最小值和最大值,但这不考虑最后一个A.

select key, min(seq), max(seq) from tblname group by key order by min(seq)

我还尝试添加另一列,以便唯一标识第二组A,但我真的不想添加另一列。 注意此处的Seq是唯一且按顺序排列。

有没有办法只用SQL做到这一点?没有程序。在此先感谢

2 个答案:

答案 0 :(得分:1)

select key,
       seq,
       (select max(seq) from ts t2
        where seq >= t1.seq
          and not exists (select 1 from ts
                          where seq between t1.seq and t2.seq
                            and key <> t1.key))
from ts t1 where not exists (select 1 from ts
                             where key = t1.key
                               and seq = t1.seq - 1);

执行为:

SQL>create table ts (seq int, key char(1));
SQL>insert into ts values (1,'A');
SQL>insert into ts values (2,'A');
SQL>insert into ts values (3,'A');
SQL>insert into ts values (4,'A');
SQL>insert into ts values (5,'B');
SQL>insert into ts values (6,'C');
SQL>insert into ts values (7,'C');
SQL>insert into ts values (8,'C');
SQL>insert into ts values (9,'C');
SQL>insert into ts values (10,'A');
SQL>insert into ts values (11,'A');
SQL>select key,
SQL&       seq,
SQL&       (select max(seq) from ts t2
SQL&        where seq >= t1.seq
SQL&          and not exists (select 1 from ts
SQL&                          where seq between t1.seq and t2.seq
SQL&                            and key <> t1.key))
SQL&from ts t1 where not exists (select 1 from ts
SQL&                             where key = t1.key
SQL&                               and seq = t1.seq - 1);

key            seq
===            ===
A                1           4
B                5           5
C                6           9
A               10          11

4 rows found

答案 1 :(得分:1)

select
  key_,
  min(seq),
  max(seq)
from (
  select
    key_,
    seq,
    sum(case when key_ = l then 0 else 1 end) over (order by seq) s
  from (
    select 
      key_,
      seq,
      lag(key_) over (order by seq) l
    from
      tq84_  /* Insert table name here */
  )
)
group by
  key_,
  s
order by
  min(seq);