查询需求是这样的:在原结果集中,如果相邻2条记录的某个属性的那2个值的差为x,则把后面那条记录剔出。用一个select语句能否直接查出来?

解决方案 »

  1.   

    是这意思吗
    with t as
    (
    select 1 a from dual
    union
    select 2 a from dual
    union
    select 3 a from dual
    union
    select 5 a from dual
    union
    select 6 a from dual
    union
    select 8 a from dual
    )select t2.a from
    (
    select rownum r,a
    from t
    ) t1
    ,
    (
    select r-1 r ,a
    from(
        select rownum r ,a
        from t
    )
    where r>1
    ) t2
    where t2.a - t1.a = 2
    and t1.r =t2.r
    ******************
    a
    ---
    5
    8
      

  2.   

    SQL> select table_name, blocks from user_tables order by table_name;TABLE_NAME                         BLOCKS
    ------------------------------ ----------
    DEPT                                    5
    EMP                                     5
    BONUS                                   0
    SALGRADE                                5
    SQL>select * from (select table_name, blocks, (lag(blocks) over(order by table_name) - blocks) minusCount from user_tables) where minusCount=2;
      

  3.   

    我试了下,这两种方法都行,但是当我把条件改为t2.a - t1.a <> 2和minusCount<>-2后,他们会把第一条记录给忽略掉,如果再用not in嵌套,我担心效率问题
      

  4.   

    那是第一个数据的前一个是没有的,所以是null,null的任何计算都是false所以就没有了,可以用nvl转一下。
    如SQL>select * from (select table_name, blocks, (nvl(lag(blocks) over(order by table_name), 0) - blocks) minusCount from user_tables) where minusCount=2;
      

  5.   

    select t2.a from 

    select rownum r,a 
    from t 
    ) t1 


    select r-1 r ,a 
    from( 
        select rownum r ,a 
        from t 

    where r>1 
    ) t2 
    where t2.a - nvl(t1.a,0) <> 2 
    and t1.r =t2.r(+)改的主要是最后两行
    where t2.a - nvl(t1.a,0) <> 2 
    and t1.r =t2.r(+)