Mid
Detailed answer
Window Functions
SQL & Databases
Write a query using LEAD and LAG.
Short answer: LAG looks at the previous row; LEAD looks at the next row within an ordered partition. Great for day-over-day diffs.
Sample solution
T-SQL
SELECT OrderDate, Amount,
LAG(Amount, 1) OVER (ORDER BY OrderDate) AS PrevAmount,
LEAD(Amount, 1) OVER (ORDER BY OrderDate) AS NextAmount,
Amount - LAG(Amount, 1) OVER (ORDER BY OrderDate) AS Delta
FROM DailySales;
Always specify ORDER BY in OVER — without it the result is nondeterministic.
Share this Q&A
Share preview image: https://www.toolliyo.com/images/toolliyo-logo.png