top of page

SQL Adv - Obtain prior or next row data

I am a fan of using ranking system to pull prior data, but if you are curious if there's another way to pull data without having to rank, then you can also use LEAD/LAG.


Here is an example code to pull prior(lagging) or next(leading) row info


CODE:


DROP TABLE IF EXISTS #blah

CREATE TABLE #blah (primkey INT PRIMARY KEY, blah varchar(10), numblah int)


INSERT INTO #blah VALUES (1, 1234567890, 10)

INSERT INTO #blah VALUES (2, 2345678910, 11)

INSERT INTO #blah VALUES (3, 3456789012, 12)

INSERT INTO #blah VALUES (4, 4567890123, 13)

INSERT INTO #blah VALUES (5, 5678901234, 14)


SELECT *,

Leadd = Lead(SUM(numblah)) OVER (ORDER BY Primkey ASC),

Lagg = Lag(SUM(numblah)) OVER (ORDER BY Primkey ASC)

FROM #blah

GROUP BY Primkey, blah, numblah


0 comments

Comments


bottom of page