How to use LAG FUNCTION in SQL SERVER 2008

房东的猫 提交于 2020-01-24 13:24:18

问题


I`m writing on SQL Server 2012 in this SQL Function

;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'

but in the first line

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

**LAG(Data) I have an Error. So I don`t know LAG() function how to use in SQL Server 2008.

Anybody Can help me ?


回答1:


Unfortunately LAG is not available to versions prior to 2012 in SQL Server. You have to use ROW_NUMBER with a self join instead:

;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


来源:https://stackoverflow.com/questions/36540642/how-to-use-lag-function-in-sql-server-2008

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!