I am puzzled over LEAD returning always ID=1, which is not even an ID in the table (ID start at ~18k), instead of a valid ID for the next record. NULL values are where they supposed to be, it's just the rows, which supposed to contain a valid ID. The LAG with the same syntax works as expected, returning correct values. The LEAD doesn't even work (correctly), when I comment out LAG. By the way, I copied the code (and just changed table and column names) from my other script, where it was working fine.
UPDATE PRJ SET
PrevJob = SRC.PrevID, -- << write Previous ID
NextJob = SRC.NextID -- << write Next ID
FROM PRJ as PRJ
LEFT JOIN (
SELECT
ID, -- << ID for joining to the original record
LAG(ID) OVER (PARTITION BY RPCode,PNInt ORDER BY OrderNo) AS PrevID, -- << previous works
LEAD(ID) OVER (PARTITION BY RPCode,PNInt ORDER BY OrderNo) AS NextID -- << next returns 1
FROM PRJ as PRJ2
) as SRC ON SRC.ID = PRJ.ID
Here is a sample of results using SELECT (see the 1 values in the last column):
ID PNInt RPCode OrderNo PrevJob NextJob
-------- ----------- -------------------- ------- -------------------- -------
18783 53 00005320171113120000 1 NULL 1
18795 53 00005320171113120000 2 18783 1
18789 53 00005320171113120000 3 18795 NULL
18784 53 00005320171127120000 1 NULL 1
18796 53 00005320171127120000 2 18784 1
18790 53 00005320171127120000 3 18796 NULL
18785 53 00005320171211120000 1 NULL 1
18797 53 00005320171211120000 2 18785 1
18791 53 00005320171211120000 3 18797 NULL
18786 53 00005320171225120000 1 NULL 1
18798 53 00005320171225120000 2 18786 1
18792 53 00005320171225120000 3 18798 NULL
18787 53 00005320180108120000 1 NULL 1
18799 53 00005320180108120000 2 18787 1
18793 53 00005320180108120000 3 18799 NULL
I fear it might be some dumb typo mistake I am blind to see. Or are there any catches with LAG and LEAD?