SQL SERVER LEAD AND LAG FUNCTION

 The following explanation from MSDN

LEAD provides access to a row at a given physical offset that follows the current row. Use this analytic function in a SELECT statement to compare values in the current row with values in a following row.

LAG provides access to a row at a given physical offset that comes before the current row. Use this analytic function in a SELECT statement to compare values in the current row with values in a previous row.


 

--A. 
SELECT Territory, _Year, Profit,
LEAD(Profit, 1, 0) OVER (PARTITION BY Territory ORDER BY _Year) AS PrevProfit
FROM Profits
--B.
SELECT Territory, _Year, Profit,
LAG(Profit, 1, 0) OVER (PARTITION BY Territory ORDER BY _Year) AS PrevProfit
FROM Profits
--C.
SELECT Territory, _Year, Profit,
LAG(Profit, 2, 0) OVER (PARTITION BY Territory ORDER BY _Year) AS PrevProfit
FROM Profits

 

First of all, compare with "LEAD" and "LAG"(A and B region code), here is the result:

Compare with 1 and 2 region only, if it's "LAG"(B region code), _Year=2002 correspondent prevProfit=2001's profit and _Year=2001 correspondent prevProfit=2000's profit, but _Year=2000 no correspondent prevProfit, as it's LAG(Profit, 1, 0), so _Year=2000 correspondent prevProfit is 0.

 

猜你喜欢

转载自www.cnblogs.com/ziqiumeng/p/10169041.html