• 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."LEAD" it's opposite of "LEAD", _Year=2000's prevProfit= 2001's Profit.

     

     2 within as to LAG(Profit, 2, 0), you can reference below code

  • 相关阅读:
    HNOI2003 消防局的设立
    APIO2007 风铃
    SDOI2006 保安站岗
    消息传递
    [POI2008]STA-Station
    JLOI2015 城池攻占
    BOI2004 sequence
    Monkey King
    APIO2012 Dispatching
    HTML meta 文本 格式排版 链接图表 列表 表单 frame后台布局实例
  • 原文地址:https://www.cnblogs.com/ziqiumeng/p/10169041.html
Copyright © 2020-2023  润新知