Did you know there is a way to find a next or previous row in SQL Server?
This short video explains how it works, and what it is very useful for
From carrying forward closing stock balances to comparing week on week sales there are lots of compelling use cases
1. Use Lead and Lag in SQL to
find previous or next rows
2. LEAD and LAG are built in analytical functions which can make
it easy to find the next or previous row of data
In this example we will use a date table as its easy to follow and
the results are plain and simple to understand
3. Here is an example
This returns the next date and the
previous date for each date in the
dataset
We will break down the components
of this code
4. Breaking down the key pieces
LEAD([FullDateUK], 1, 0) over (ORDER BY [datekey]) as nextday
LEAD looks for the next row
[FullDateUK] is the field we want to return
, 1 is the number of rows to look forward
, 0 is the default if no data is available
over (ORDER BY [datekey]) defines the order to sort the data
LAG is very similar, except that it looks for the previous row
5. Other examples
select [FullDateUK], nextweek, prevweek from
(
SELECT [datekey], [FullDateUK]
, LEAD([FullDateUK], 7,0) over (ORDER BY [datekey]) as nextweek
, LAG([FullDateUK], 7,0) over (ORDER BY [datekey]) as prevweek
FROM [SelectDistinctTips].[dbo].[DimDate]
) D
where [datekey] > 20191225
order by [datekey]
By changing the parameter to a 7 we can return the date a week
earlier
6. Use Cases
You wouldn’t use this technique to find dates as there are date functions to do that, but it does demonstrate nicely how
it works
Typical use cases for this
Finding the prior week or month sales for a sales dataset, Forecasting closing stock by carrying forward the previous
days closing stock
It can be used wherever you need to find either the previous row and or next row of a dataset, like you might do in
Excel