lag() over() 與lead() over() 函數是跟偏移量相關的兩個分析函數,通過這兩個函數可以在一次查詢中取出同一字段的前N行的數據(lag)和後N行的數據(lead)作爲獨立的列,從而更方便地進行進行數據過濾。這種操作可以代替表的自聯接,並且LAG和LEAD有更高的效率。
over()表示 lag()與lead()操作的數據都在over()的範圍內,他裏面可以使用partition by 語句(用於分組) order by 語句(用於排序)。partition by a order by b表示以a字段進行分組,再 以b字段進行排序,對數據進行查詢。
例如:lead(field, num, defaultvalue) field需要查找的字段,num往後查找的num行的數據,defaultvalue沒有符合條件的默認值
1.獲取當前記錄的id,以及下一條記錄的id
select t.id,lead(t.id,1,null) over(order by t.id) next_record_id ,t.cphm from test t order by t.id asc
2.獲取品牌號碼相同的,當前記錄的id和下一條記錄的id
select t.id,lead(t.id,1,null) over(partirion by t.cphm order by t.id desc) next_same_cphm_id,t.cphm from test order by t.id asc
3.查詢 cphm的總數,當create_date與下一條記錄的create_date時間間隔不超過10分鐘則忽略
select cphm, count(1) total from
(
select t.id,
t.create_date t1,
lead(t.create_date,1, null) over( partition by cphm order by create_date asc ) t2,
( lead(t.create_date,1, null) over( partition by cphm order by create_date asc ) - t.create_date ) * 86400 as itvtime,
t.cphm
from tb_test t
order by t.cphm, t.create_date asc
) tt
where tt.itvtime >= 600 or tt.itvtime is null
group by tt.cphm