如何在不使用虚拟表概念的情况下优化后续查询

时间:2012-10-23 08:34:50

标签: sql db2

以下是使用虚拟概念的查询,但我想要其优化的表单,而不使用“虚拟表”概念。

 with TEMP AS
          (

          Select RN from                                                            
          (                                                                         
          SELECT TCTITL,                                                            
          ROW_NUMBER() OVER ( ORDER BY TCTITL asc ) AS RN FROM PVTC ORDER BY        
          TCTITL asc                                                                
          )T 

          WHERE ((TCTITL >= 'AAPS  ' ))                                             
          ORDER BY TCTITL asc fetch first row only  )  

          , mytab as
          (

          Select * from
          (                                                           
         ( SELECT TCTITL, TCEDUR, TCSTZF, TCTTLE, TCLSHN, TCCEQ3,                  
        ROW_NUMBER() OVER ( ORDER BY TCTITL asc ) AS RN                           
         FROM PVTC ORDER BY TCTITL asc  )                                          
          ) Q

          ,  TEMP where Q.RN                                                     
          between (TEMP.RN + 0) and ( TEMP.RN + 3)                                  
          )
          select * from mytab  

注意:我的表有结果说1到10,但我想要两个指针之间的结果只说3到10.这是这个查询的目标。

更新:我有五条记录,我想根据Row_Number 2选择1 t0 5之间的记录。(其中1,2,3,4,5显示Row_number)

   col1    col2    col3 
    a   b   c   
    a1  b1  c1  
    -------------------------
    ---------------------------
    --------------------------
    a5  b5  c5  

1 个答案:

答案 0 :(得分:0)

您似乎只想获取tctitl >= 'AAPS '所在的前四行,以及描述其在表中排名的行号。如果是这样,我认为这样可以解决问题:

select * from (
        select pvtc.*, row_number() over (order by tctitl) as rn from pvtc 
    )
    where (tctitl >= 'AAPS  ' )                                             
    order by tctitl
    fetch first four rows only;