如何通过形成查询来获取数据?

时间:2017-10-31 06:13:11

标签: sql oracle oracle11g window-functions

table data:
  sno  data
    1  a
    2  b
    3  c
    5  d
    6  e
    8  f

result is :

l-side    r-side
a           b
c           null
d           e
null        f

我试过LEAD AND LAG ..

  select sno,
    lead(data,1) over(partition by data order by sno RANGE BETWEEN 1 PRECEDING AND 1 FOLLOWING) as l-side,
    lag(data,1) over(partition by data order by sno RANGE BETWEEN 2 PRECEDING AND 1 FOLLOWING) as r-side
    from table

但它给出了我所要求的不同之处。根据我的结果形成查询。

2 个答案:

答案 0 :(得分:1)

我的解决方案:

with t as (
  select 1 as sno, 'a' as data from dual
  union all
  select 2 as sno, 'b' as data from dual
  union all
  select 3 as sno, 'c' as data from dual
  union all
  select 5 as sno, 'd' as data from dual
  union all
  select 6 as sno, 'e' as data from dual
  union all
  select 8 as sno, 'f' as data from dual
)
,
inum as (
  select level as s1, level+1 as s2 from dual
  where mod(level,2) = 1
  connect by level <= (select max(sno) from t)
)

select t.data as l_side, t1.data as r_side
from inum left join t on inum.s1 = t.sno
          left join t t1 on inum.s2 = t1.sno
order by s1

输出:

 L_SIDE R_SIDE
    a   b
    c   - 
    d   e
    -   f

答案 1 :(得分:1)

试试这个。

WITH ut 
     AS (SELECT t.*, 
                rownum rn 
         FROM   yourtable t) 
SELECT a.data, 
       b.data 
FROM   (SELECT data, 
               rn 
        FROM   ut 
        WHERE  MOD(sno, 2) = 1) a 
       FULL OUTER JOIN (SELECT data, 
                               rn 
                        FROM   ut 
                        WHERE  MOD(sno, 2) = 0) b 
                    ON a.rn + 1 = b.rn 
ORDER  BY a.rn;