简体   繁体   English

如何使用 LAG 函数进行 STDEV 计算?

[英]How to do a STDEV calculation with the LAG function?

I'm running code like this:我正在运行这样的代码:

SELECT ID, Date, Price,
    STDEV(Price) OVER (ORDER BY ID, Date ROWS BETWEEN 30 PRECEDING AND CURRENT ROW) As OneMonths,
    STDEV(Price) OVER (ORDER BY ID, Date ROWS BETWEEN 60 PRECEDING AND CURRENT ROW) As TwoMonths,
    STDEV(Price) OVER (ORDER BY ID, Date ROWS BETWEEN 90 PRECEDING AND CURRENT ROW) As ThreeMonths
FROM Price_Table

That gives me this result.这给了我这个结果。

在此处输入图片说明

In the fiver first row I always have three nulls for the three variances.在第一行中,对于三个方差,我总是有三个空值。 This makes sense.这是有道理的。 However, every time the ID changes, I must be getting the preceding ID's prices, because each time the ID changes, I would expect the standard deviation to get reset.但是,每次 ID 更改时,我都必须获得前一个 ID 的价格,因为每次 ID 更改时,我都希望标准偏差会重置。 So, the first line in orange should be null, I think, and the next one should be zero, because there is no change in price the second day.所以,橙色​​的第一行应该是空的,我认为下一行应该是零,因为第二天价格没有变化。 I tried wrapping the LAG function around the STDEV function and I got an error.我尝试将 LAG 函数包装在 STDEV 函数周围,但出现错误。 I tried the opposite and also got an error.我尝试了相反的方法,也出现了错误。

If you want the value per id , then you need partition by :如果你想要每个 id的值,那么你需要partition by

SELECT ID, Date, Price,
       STDEV(Price) OVER (PARTITION BY ID ORDER BY Date ROWS BETWEEN 30 PRECEDING AND CURRENT ROW) As OneMonths,
       STDEV(Price) OVER (PARTITION BY ID ORDER BY Date ROWS BETWEEN 60 PRECEDING AND CURRENT ROW) As TwoMonths,
       STDEV(Price) OVER (PARTITION BY ID ORDER BY Date ROWS BETWEEN 90 PRECEDING AND CURRENT ROW) As ThreeMonths
FROM Price_Table;

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

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