下文讲述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 lead使用说明及简介

mssql_sqlserver_lag详解举例-1


—————————————

mssql sqlserver 分析函数lag lead使用说明及简介

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 分析函数lag lead使用说明及简介

mssql_sqlserver_lead详解举例-1

相关文章:

  • 2021-04-14
  • 2021-10-17
  • 2021-07-27
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-07-24
  • 2022-12-23
猜你喜欢
  • 2021-09-22
  • 2021-12-09
  • 2022-12-23
  • 2021-07-03
  • 2021-05-25
  • 2022-12-23
相关资源
相似解决方案