oracle中lag()函數和lead()函數的用法____靜態函數

來源:互聯網
上載者:User

lag和lead函數可以在同一次查詢中取出同一欄位的前N行資料(lag)和後N行資料(lead)。這種欄位可以使用對相同表的表串連來實現,不過使用lag和lead函數具有更高的效率。

文法:

LAG(EXP_STR,OFFSET,DEFVAL)OVER()

LEAD(EXP_STR,OFFSET,DEFVAL)OVER()
EXP_STR:要取的列
OFFSET: 取位移後的第幾行資料
DEFVAL:沒有合格預設值

例如:

指令碼一:

--使用相同的表串連來實現

select a.c_month,a.c_soto, a.kpi_value, a1.kpi_value kpi_value_s --上月
  from dm_custbd_index_month a
  left join dm_custbd_index_month a1
    on a1.index_id = 'CUSIND_FUL001'
   and a.c_soto = a1.c_soto
   and a.c_month = a1.c_month + 1
 where a.index_id = 'CUSIND_FUL001'
   and a.c_soto = '8800155164';

-----------

指令碼二:

--使用lag函數來實現

 select a.c_month,a.c_soto,a.kpi_value,lag(a.kpi_value,1)over(order by a.c_month) --上月
     from dm_custbd_index_month a
    where a.index_id = 'CUSIND_FUL001'
      and a.c_soto = '8800155164';

這兩個指令碼的查詢結果是一樣的,都是查上個月的指標值。相對來說指令碼二代碼簡單而且執行效率更高。 結果:



lead()函數求後N行資料,同理:


select a.c_month,a.c_soto, a.kpi_value, a1.kpi_value kpi_value_x --下月
  from dm_custbd_index_month a
  left join dm_custbd_index_month a1
    on a1.index_id = 'CUSIND_FUL001'
   and a.c_soto = a1.c_soto
   and a.c_month = a1.c_month- 1
 where a.index_id = 'CUSIND_FUL001'
   and a.c_soto = '8800155164';
   
   
   select a.c_month,a.c_soto,a.kpi_value,lead(a.kpi_value,1)over(order by a.c_month)  kpi_value_x--下月
     from dm_custbd_index_month a
    where a.index_id = 'CUSIND_FUL001'
      and a.c_soto = '8800155164';


結果都是:






聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.