Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
290 views
in Technique[技术] by (71.8m points)

sql - Group by values that are in sequence

I have some table like this

row chequeNo
 1     15
 2     19
 3     20
 4     35
 5     16

and I need to get the result like this

row  from   to    
 1    15    16     
 2    19    20    
 3    35    35

so I need groups of chequeNo where values would be sequential without any interruptions. chequeNo is unique column. Additionally it should be done with one sql select query, because I haven't permissions to create any sql structures except select queries.

So is it possible?

Would be grateful for any help

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use Aketi Jyuuzou's technique called Tabibitosan here:

SQL> create table mytable (id,chequeno)
  2  as
  3  select 1, 15 from dual union all
  4  select 2, 19 from dual union all
  5  select 3, 20 from dual union all
  6  select 4, 35 from dual union all
  7  select 5, 16 from dual
  8  /

Table created.

SQL> with tabibitosan as
  2  ( select chequeno
  3         , chequeno - row_number() over (order by chequeno) grp
  4      from mytable
  5  )
  6  select row_number() over (order by grp) "row"
  7       , min(chequeno) "from"
  8       , max(chequeno) "to"
  9    from tabibitosan
 10   group by grp
 11  /

       row       from         to
---------- ---------- ----------
         1         15         16
         2         19         20
         3         35         35

3 rows selected.

Regards,
Rob.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...