简体   繁体   English

SQL Server 2008中的滞后功能

[英]LAG FUNCTION in SQL Server 2008

I`m writing on SQL Server 2012 in this SQL function 我正在使用此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', '1')
)
SELECT 
    [Quote].[SID], Quote.DATE, Quote.DATA, Quote.SHEET, Quote.CODE,
    CASE 
       WHEN ISNULL(LastMonthData, 0) = 0 THEN null 
       ELSE (Data-LastMonthData)/LastMonthData
    END As Quote
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 '2014/01/01' and '2016/12/01'

but on the first line 但在第一行

;With Quote as (
SELECT SID,SHEET,Code, Date, Data, 
       LAG(Data) OVER(ORDER BY Date) As LastMonthData 
       FROM RMQ_DATA WHERE [SHEET] IN('0','1'))

LAG(Data) I have an error. LAG(Data)我有一个错误。 So I don't know LAG() function how to use in SQL Server 2008. 因此,我不知道LAG()函数如何在SQL Server 2008中使用。

How can I solve this trouble ? 我该如何解决这个麻烦?

If you can't execute this in SQL Server 2012 meaning you can't use LAG function, AND you know that the "Date" data doesn't have ANY gaps, then a workaround is to self-join the same table. 如果您无法在SQL Server 2012中执行此操作,这意味着您无法使用LAG函数,并且您知道“日期”数据之间没有任何间隙,那么一种解决方法是自联接同一张表。

for eg, instead of this 例如,代替这个

SELECT 
    SID, SHEET, Code, Date, Data, 
    LAG(Data) OVER(ORDER BY Date) As LastMonthData 
FROM 
    RMQ_DATA 
WHERE 
    [SHEET] IN ('0', '1')

use something like this 用这样的东西

select A.SID, A.SHEET, A.Code, A.Date, A.Data as ThisMonthData, B.Data as LastMonthData from RMQ_DATA A, RMQ_DATA B where A.sid= B.sid and A.sheet=B.sheet and A.date=add_months(B.Date,1) where [SHEET] IN ('0', '1') 从RMQ_DATA A,RMQ_DATA B中选择A.SID,A.SHEET,A.Code,A.Date,A.Data作为ThisMonthData,B.Data作为LastMonthData,其中A.sid = B.sid和A.sheet = B.sheet和A.date = add_months(B.Date,1),其中[SHEET] IN('0','1')

add_months is an Oracle function, and might not be right for your dates anyway, but you get the idea. add_months是一个Oracle函数,可能无论如何都不适合您的日期,但是您明白了。

If the Date data has any gap in it, then this won't work, you will miss rows - you'd need to join some kind of row generator to make this work. 如果Date数据中有任何间隙,那么它将无法正常工作,您将错过行-您需要加入某种行生成器才能进行此工作。 It gets ugly fast, as marc_s said. 正如marc_s所说的,它变得丑陋得很快。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM