ID SEQ DEPT
1901 010 401
1902 020 280
1903 030 402
1904 040 402
1905 050 402
1906 060 402
1907 070 280
1908 080 411
1909 090 280
该表是根据seq排序,
获得一个ID,如1907,通过该ID找到对应的dept 280,通过dept向上找相等280,查询出两个280之间的数据,包括ID为1907的数据,根据seq排序。
得到的结果是
1903 030 402
1904 040 402
1905 050 402
1906 060 402
1907 070 280上次请教过一个类似的问题,上次是根据ID排序,怎么改成按SEQ排序就不行,百思不得其解,只能再麻烦高人相助了。
在下在此深表谢意
上次根据ID排序的代码如下
select a.*
from tb a,(select dept,id,id2
from (select dept,id,lag(id,1) over(partition by dept order by id) id2
from tb) where id=1907) b
where a.id>b.id2 and a.id<=b.id
1901 010 401
1902 020 280
1903 030 402
1904 040 402
1905 050 402
1906 060 402
1907 070 280
1908 080 411
1909 090 280
该表是根据seq排序,
获得一个ID,如1907,通过该ID找到对应的dept 280,通过dept向上找相等280,查询出两个280之间的数据,包括ID为1907的数据,根据seq排序。
得到的结果是
1903 030 402
1904 040 402
1905 050 402
1906 060 402
1907 070 280上次请教过一个类似的问题,上次是根据ID排序,怎么改成按SEQ排序就不行,百思不得其解,只能再麻烦高人相助了。
在下在此深表谢意
上次根据ID排序的代码如下
select a.*
from tb a,(select dept,id,id2
from (select dept,id,lag(id,1) over(partition by dept order by id) id2
from tb) where id=1907) b
where a.id>b.id2 and a.id<=b.id
SQL>
SQL> with tab as (
2 select 1901 id, 010 SEQ ,401 DEPT from dual union all
3 select 1902 id, 020 SEQ ,280 DEPT from dual union all
4 select 1903 id, 030 SEQ ,402 DEPT from dual union all
5 select 1904 id, 040 SEQ ,402 DEPT from dual union all
6 select 1905 id, 050 SEQ ,402 DEPT from dual union all
7 select 1906 id, 060 SEQ ,402 DEPT from dual union all
8 select 1907 id, 070 SEQ ,280 DEPT from dual union all
9 select 1908 id, 080 SEQ ,411 DEPT from dual union all
10 select 1909 id, 090 SEQ ,280 DEPT from dual
11 )
12 select id, seq, dept
13 from tab a,
14 (select max(seq) ed, min(seq) sd
15 from (select id,
16 seq,
17 dept,
18 row_number() over(partition by dept order by id desc) rn
19 from tab k
20 where dept in (select dept from tab t where t.id = 1909)
21 and id <= 1909)
22 where rn <= 2) b
23 where a.seq > b.sd
24 and a.seq <= b.ed
25 ; ID SEQ DEPT
---------- ---------- ----------
1908 80 411
1909 90 280SQL>
--类似的啊,将ID排序改成以SEQ排序
select a.*
from tb a,(select dept,id,seq,seq2
from (select dept,id,seq,lag(seq,1) over(partition by dept order by seq) seq2
from tb) where id=1907) b
where a.seq>b.seq2 and a.seq<=b.seq