求某個列第2大的值的多種方法

 



  1.     create table t (x int);  --創建測試表  
  2.     insert into t values(1);   
  3.     insert into t values(3);   
  4.     insert into t values(5);   
  5.     insert into t values(7);   
  6.     insert into t values(9);   
  7.     法一:  
  8.     select x  
  9.         from ( select x, rownum r  
  10.                  from ( select x from t order by x desc )  
  11.                         where rownum <= 2 )  
  12.        where r = 2;  
  13.     註釋:子查詢不進行擴展(unest),那麼是先求出最裏層的數據  
  14.     法二:  
  15.     select *     
  16.      from t     
  17.      where (select count(*)    
  18.      from t t2     
  19.      where t2.x > t.x ) = 1     
  20.      /   
  21.     註釋:子查詢中的條件跟其他高輩分的SELECT有關聯(關聯子查詢) 
  22. 法三: 
  23. select max(x)  
  24.  from t  
  25.  where x < (select max(x) from t)  
  26.  / 
  27. 法四: 
  28. select x  
  29.  from ( select x, row_number() over ( order by x desc ) r  
  30.           from t  
  31.         )  
  32.  where r = 2  
  33. 註釋:row_number() 是分析函數 
  34.  
  35.   

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章