Oracle分析函數-first_value()和last_value()


first_value()和last_value()字面意思已經很直觀了,取首尾記錄值。
例:查詢部門最早發生銷售記錄日期和最近發生的銷售記錄日期

select
       dept_id
      ,sale_date
      ,goods_type
      ,sale_cnt
      ,first_value(sale_date) over (partition by dept_id order by sale_date) first_value
      ,last_value(sale_date) over (partition by dept_id order by sale_date desc) last_value
from criss_sales;

看結果first_value()很直觀,不用多解釋
但是,last_value()值,部門D01不是應該為2014/6/12,部門D02不是應該為2014/5/2嗎?為什么會每條記錄都不一樣?
可以這樣去理解:last_value()默認統計范圍是 rows between unbounded preceding and current row
驗證一下:

select
       dept_id
      ,sale_date
      ,goods_type
      ,sale_cnt
      ,first_value(sale_date) over (partition by dept_id order by sale_date) first_value
      ,last_value(sale_date) over (partition by dept_id order by sale_date desc) last_value
      ,last_value(sale_date) over (partition by dept_id order by sale_date rows between unbounded preceding and unbounded following) last_value_all
from criss_sales;

全統計的情況下得到的last_value()值,部門D01為2014/6/12,部門D02為2014/5/2。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM