oracle lag使用情景,lag函数用法
摘要:
下文講述sqlserver 2012中 lag、lead分析函數的用法及簡介
實驗環境: sqlserver 2012
lag、lead:
可以不通過聯結的形式獲取上下相鄰(指定偏移量)行的指定列的數據
lag 向前指定數據
lead向后指定數據
——————–
lag、lead參數說明:
參數1:列名
參數2:偏移量offset
參數3:進行偏移量計算后,無法得到結果時的缺省值
例:
lag分析函數舉例說明
declare @test table(keyId int,info varchar(20),qty int)
insert into @test (keyId,info,qty)values(-1,'a',2)
insert into @test (keyId,info,qty)values(1,'a',2)
insert into @test (keyId,info,qty)values(2,'a',10)
insert into @test (keyId,info,qty)values(3,'b',8)
insert into @test (keyId,info,qty)values(3,'b',8)
insert into @test (keyId,info,qty)values(5,'d',8)
insert into @test (keyId,info,qty)values(6,'b',9)
/*
例: lag 在info群組中,
向前偏移一行, 無法找到值時,使用默認值"-9"
keyId=-1 在info ='a'群組中,向前偏移一行,無數據,所以為默認值-9
keyId=1 在info ='a'群組中,向前偏移一行,上一行數據為-1 所以顯示-1
keyId=2 在info ='a'群組中,向前偏移一行,上一行數據為-1 所以顯示-1
keyId=3 在info ='b'群組中,向前偏移一行,無數據,所以為默認值-9
keyId=3 在info ='b'群組中,向前偏移一行,上一行數據為-1 所以顯示3
keyId=6 在info ='b'群組中,向前偏移一行,上一行數據為-1 所以顯示3
keyId=5 在info ='d'群組中,向前偏移一行,無數據,所以為默認值-9
*/
select *,
lag(keyId,1,'-9') over(partition by info order by keyId) as lagInfo
from @test
mssql_sqlserver_lag詳解舉例-1
—————————————
mssql_sqlserver_lag詳解舉例-2
lead分析函數舉例說明
lead 向后查找指定列數據,作為返回值,同lag的唯一區別為:查找方向不一樣
declare @test table(keyId int identity,info varchar(20),qty int)
insert into @test (info,qty)values('a',2)
insert into @test (info,qty)values('a',2)
insert into @test (info,qty)values('a',10)
insert into @test (info,qty)values('b',8)
insert into @test (info,qty)values('b',8)
insert into @test (info,qty)values('d',8)
insert into @test (info,qty)values('b',9)
select *,
lead(keyId,1,'-9') over(order by keyId) as lagInfo
from @test
mssql_sqlserver_lead詳解舉例-1
總結
以上是生活随笔為你收集整理的oracle lag使用情景,lag函数用法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Linux下的lds链接脚本二
- 下一篇: 2021年全国职业院校技能大赛(中职组)