SQL SERVER LEAD和LAG函数

sql server中LEAD和LAG函数可直接获取当前数据上下相邻多少行数据。见以下案例:

--测试数据
if not object_id(N'Tempdb..#T') is null drop table #T
Create table #T([Id] int,[Value] int)
Insert #T
select 1,10 union all
select 2,20 union all
select 3,30 union all
select 4,40 union all
select 5,50
结果如图:

语法以LEAD为例:LEAD ( scalar_expression [ ,offset ] , [ default ] ) OVER ( [ partition_by_clause ] order_by_clause ),读取的数据,偏移多少行,如果没有值默认值是多少

SELECT *,
       LEAD(Value, 1, 666) OVER (ORDER BY Value) AS LEADVALUE,  --提前1行,默认值666
       LAG(Value, 2, 888) OVER (ORDER BY Value) AS LAGVALUE  --滞后2行,默认值888
FROM #T;
结果如下:

你可能感兴趣的:(sql,server,sql,数据库,database)