zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    PHP多维数组转为一维数组的方法实例
    PHP内存模拟分析
    linux windows mysql安装
    Ubuntu 连接Xshell 不能连接
    Linux软链挂载
    python 数据库连接 CRUD
    RabbitMQ 实现广播订阅
    Redis 实现广播订阅
    python-切片
    python中的3目运算(3元表达式)
  • 原文地址:https://www.cnblogs.com/ziqiumeng/p/10169041.html
Copyright © 2011-2022 走看看