2,668
社区成员
发帖
与我相关
我的任务
分享
create table test(id int primary key);
insert into test values(1);
insert into test values(2);
insert into test values(3);
insert into test values(4);
insert into test values(5);
insert into test values(6);
insert into test values(8);
insert into test values(9);
insert into test values(11);
insert into test values(12);
insert into test values(17);
insert into test values(19);
select max(decode(mod(t01.rn,2),1,t01.cid,null)) as id1,
max(decode ( mod (t01.rn,2),0,t01.cid,null)) as id2
from
(
select t4.cid,rownum rn
from
(
select t3.cid from
(
select t1.*
from
(
select test.id as cid, (id-nvl(lag(id,1) over(order by id),0)) as pmis , (nvl(lead(id,1) over(order by id),id+1)-id) as nmis from test
) t1 where t1.pmis!=1 or t1.nmis!=1
union all
select t2.*
from
(
select test.id as cid, (id-nvl(lag(id,1) over(order by id),0)) as pmis , (nvl(lead(id,1) over(order by id),id+1)-id) as nmis from test
) t2 where t2.pmis!=1 and t2.nmis!=1
)t3 order by t3.cid asc
)t4 order by t4.cid asc
)t01 group by TRUNC((t01.rn+1)/2)
order by TRUNC((t01.rn+1)/2)
--结果如下:
id1 id2
---------- ----------
9 11
12 17
17 19
--得到何波(hebo2005)的指点,何波(hebo2005)所写sql如下,就是2行一列变成1行两列,我在最外层用到:
SELECT MAX (DECODE (MOD (rn, 2), 1, ID, null)) one,
MAX (DECODE (MOD (rn, 2), 0, ID, null)) two
FROM (SELECT ROWNUM rn, aa.*
FROM (SELECT a.ID
FROM test a
ORDER BY ID) aa)
GROUP BY TRUNC ((rn + 1) / 2)
ORDER BY TRUNC ((rn + 1) / 2)
9 11
12 17
17 19