试图让滞后分区显示以前的值

时间:2019-01-21 15:24:17

标签: sql-server

我正在尝试在某个分区中获取先前的值。

我试图对Lag Partition over子句进行操作,但它仍然使我为NULL。

1 个答案:

答案 0 :(得分:0)

LAG是MS SQl Server 2012中引入的出色的窗口功能。 https://docs.microsoft.com/en-us/sql/t-sql/functions/lag-transact-sql?view=sql-server-2017

    DECLARE @Table TABLE (BusinessEntityID int, SalesYear int,   SalesQuota decimal);
    INSERT INTO @Table  (BusinessEntityID, SalesYear, SalesQuota)
    VALUES
     (275,2005,367000)
    ,(275,2005,556000)
    ,(275,2006,502000)
    ,(275,2006,550000)
    ,(275,2006,1429000)
    ,(275,2006,1324000);

    SELECT BusinessEntityID, SalesYear AS SalesYear, SalesQuota AS CurrentQuota,   
           LAG(SalesQuota, 1,0) OVER (ORDER BY SalesYear) AS PreviousQuota  
    FROM @Table
    WHERE BusinessEntityID = 275 and SalesYear IN ('2005','2006');  

执行查询的结果:

   BusinessEntityID SalesYear   CurrentQuota    PreviousQuota
   275                  2005    367000                0
   275                  2005    556000                367000
   275                  2006    502000                556000
   275                  2006    550000                502000
   275                  2006    1429000               550000
   275                  2006    1324000               1429000