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

  • 相关阅读:
    C# 视频监控系列(11):H264播放器——封装API[HikPlayM4.dll]
    php框架
    ExtJS带验证码登录框[新增回车提交]
    ant 读取环境变量的值
    Apache Velocity实现模板化
    23种设计模式概述
    android资源下载
    无序hashset与hashmap让其有序
    PermGen space错误解决方法
    设计模式之代理模式(Proxy)
  • 原文地址:https://www.cnblogs.com/ziqiumeng/p/10169041.html
Copyright © 2011-2022 走看看