簡體   English   中英

SQL 在間隙重新啟動的滾動平均值

[英]SQL rolling average that restarts on gaps

我有每 1 小時出現一次的值,我需要做一個 8 小時的滾動平均值。 問題是,當出現差距時,這個滾動平均值必須“重新開始”。

請參閱下表(我想要的輸出),如您所見,缺少 14:45 的值,因此 15:45 的平均值是該行的 Scaled。

然后缺少 16:45、17:45、18:45 和 19:45 值,因此 20:45 的值是該行的 Scaled。

21:45 是 20:45 和 21:45 之間的平均值。

22:45 是 20:45、21:45 和 22:45 之間的平均值。

等等...

開始日期 縮放 滾動平均
2021-01-28 00:45:00.000 10.589 10.589
2021-01-28 01:45:00.000 9.989 10.289000000000001
2021-01-28 02:45:00.000 10.512 10.363333333333335
2021-01-28 03:45:00.000 10.22 10.3275
2021-01-28 04:45:00.000 13.23 10.9080000000000001
2021-01-28 05:45:00.000 14.516 11.509333333333336
2021-01-28 06:45:00.000 15.687 12.106142857142858
2021-01-28 07:45:00.000 14.316 12.382375000000001
2021-01-28 08:45:00.000 16.888 13.169750000000002
2021-01-28 09:45:00.000 24.58 14.993625000000002
2021-01-28 10:45:00.000 24.349 16.72325
2021-01-28 11:45:00.000 22.832 18.29975
2021-01-28 12:45:00.000 26.166 19.91675
2021-01-28 13:45:00.000 27.437 21.531875
2021-01-28 15:45:00.000 22.424 22.424
2021-01-28 20:45:00.000 19.629 19.629
2021-01-28 21:45:00.000 21.431 20.53
2021-01-28 22:45:00.000 22.07 21.04333333

我需要把這個 go 放到一個視圖中,所以我不能使用變量。

我找不到辦法,所以任何幫助將不勝感激。

謝謝!

您可能會發現蠻力方法最簡單:

select t.*, v.avg_scaled
from (select t.*,
             lag(scaled, 1) over (order by startdate) as scaled_1,
             lag(scaled, 2) over (order by startdate) as scaled_2,
             . . .
             lag(startdate, 1) over (order by startdate) as startdate_1,
             lag(startdate, 2) over (order by startdate) as startdate_2,
             . . .
             
      from t
     ) t cross apply
     (select avg(v.scaled) as avg_scaled
      from (values (0, t.scaled, t.startdate),
                   (1, t.scaled_1, t.startdate_1),
                   (2, t.scaled_2, t.startdate_2),
                   . . .
           ) v(n, scaled, startdate)
       where datediff(hour, v.start_date, t.startdate) = v.n
     ) v;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM