Note: I am using SQL Server 2008 R2 and built in LEAD/LAG functions are not available.
I need to update a table's column to contain the 'previous' and 'next' values for ProductID - the table needs to store PrevProductID (LAG), ProductID and NextProductID (LEAD). The code below does this very nicely and was adapted from Geri Reshef's answer to http://blog.sqlauthority.com/2011/11/24/sql-server-solution-to-puzzle-simulate-lead-and-lag-without-using-sql-server-2012-analytic-function/
USE AdventureWorks2008R2
GO
WITH T1 AS
( SELECT Row_Number() OVER(ORDER BY SalesOrderID,ProductID) N,
s.SalesOrderID,
s.ProductID
FROM Sales.SalesOrderDetail s
WHERE SalesOrderID IN (43670, 43667, 43663)
)
SELECT SalesOrderID,
CASE WHEN N%2=1
THEN MAX(CASE WHEN N%2=0
THEN ProductID
END) OVER (Partition BY N/2)
ELSE MAX(CASE WHEN N%2=1
THEN ProductID
END) OVER (Partition BY (N+1)/2)
END PrevProductID,
ProductID,
CASE WHEN N%2=1
THEN MAX(CASE WHEN N%2=0
THEN ProductID
END) OVER (Partition BY (N+1)/2)
ELSE MAX(CASE
WHEN N%2=1 THEN ProductID
END) OVER (Partition BY N/2)
END NextProductID
FROM T1
ORDER BY
t1.SalesOrderID,
t1.ProductID
These are the results and the Lag/Lead are applied to all rows.
SalesOrderID PrevProductID ProductID NextProductID
------------ ------------- ----------- -------------
43663 NULL 760 710
43667 760 710 773
43667 710 773 775
43667 773 775 778
43667 775 778 709
43670 778 709 710
43670 709 710 773
43670 710 773 776
43670 773 776 NULL
What I need to do is to group the Lag/Lead values by SalesOrderID with the first occurrence pointing to Lag of NULL and the last occurrence pointing to Lead of NULL within a SalesOrderID group.
SalesOrderID PrevProductID ProductID NextProductID
------------ ------------- ----------- -------------
43663 NULL 760 NULL
43667 NULL 710 773
43667 710 773 775
43667 773 775 778
43667 775 778 NULL
43670 NULL 709 710
43670 709 710 773
43670 710 773 776
43670 773 776 NULL