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';
結果都是: