I continue a series on window functions:
Offset functions are another class of window function in SQL Server thanks to being part of the ANSI SQL standard. Think of a window of data, stretching over some number of rows. What we want to do is take the current row and then look back (or “lag” the data) or forward (“lead”).
There are four interesting offset window functions:
LAG()
,LEAD()
,FIRST_VALUE()
, andLAST_VALUE()
. All four of these offset functions require anORDER BY
clause because of the nature of these functions.LAG()
andLEAD()
take two parameters, one of which is required. We need to know the value to lag/lead, so that’s a mandatory parameter. In addition, we have an optional parameter which indicates how many steps forward or backward we want to look. Let’s see this in action with a query:
Click through for that query, as well as a few more and plenty of explanation.
Comments closed