一尘不染

如何在SQL SERVER 2008中使用滞后功能

sql

我正在此SQL函数中编写SQL Server 2012

;With Quote as (
   SELECT SID,SHEET,Code, Date, Data, 
          LAG(Data) OVER(ORDER BY Date) As LastMonthData 
   FROM RMQ_DATA WHERE [SHEET] IN(0)
)
SELECT [Quote].[SID], Quote.DATE,Quote.DATA,Quote.SHEET, Quote.CODE,
       CASE 
          WHEN ISNULL(LastMonthData, 0) = 0 THEN null 
          ELSE (LastMonthData/Data) * 100 
       END As Quote,
       RMQ_SUBCAT.TARGET_CODE, RMQ_SUBCAT.RMQ_SUBCAT, RMQ_CAT.RMQ_CAT_NAME, 
       RMQ_CAT.ENABLED
FROM Quote
Left outer Join RMQ_SUBCAT on  Quote.CODE =RMQ_SUBCAT.TARGET_CODE
left outer join RMQ_CAT on RMQ_SUBCAT.TARGET_SID=RMQ_CAT.SID
where RMQ_CAT.ENABLED='Y' and 
      Quote.DATE between '2015/01/01' and '2015/11/01'

但在第一行

With Quote as ( 
   SELECT SID,SHEET,Code, Date, Data, 
          LAG(Data) OVER(ORDER BY DATE)

** LAG(Data)我有一个错误。所以我不知道如何在SQL Server 2008中使用LAG()函数。

有人可以帮我吗?


阅读 187

收藏
2021-03-08

共1个答案

一尘不染

遗憾的LAG是,SQL Server 2012之前的版本不可用。您必须使用ROW_NUMBER自连接来代替:

;With Quote as (
   SELECT SID, SHEET,Code, [Date], Data,
          ROW_NUMBER() OVER (ORDER BY [Date]) AS rn
   FROM RMQ_DATA 
   WHERE [SHEET] IN (0)
), Quote_LAG AS (
   SELECT q1.SID, q1.SHEET, q1.Code, q1.[Date], q1.Data,
          q2.Data AS LastMonthData
   FROM Quote AS q1
   LEFT JOIN Quote AS q2 ON q1.rn = q2.rn + 1
)
... rest of the query here
2021-03-08