sql 服务器的三天滚动平均值

rolling three day average in sql server

我想找到三天的平均值。预期输出:

dt amt running_avg
2022-05-1 100 0
2022-05-2 150 0
2022-05-3 50 100
2022-05-14 250 150
2022-05-15 0 100

应计算 3 天的平均值 window。我的查询是:

select a.dt, avg(b.amt) over(order by a.dt ) as running_avg,b.amt
from trans a
left join trans b on b.dt = a.dt
where a.dt between DATEADD(day,-3, a.dt) and getdate()

我的查询只是给出正常的 运行 平均值,而不是 3 天的平均值。让我知道如何在 SQL 服务器中完成此操作。

谢谢!

您似乎需要 ROWS/RANGE 窗口中的参数 AVG():

数据:

SELECT *
INTO trans
FROM (VALUES
   (CONVERT(date, '20220501'), 100),
   (CONVERT(date, '20220502'), 150),
   (CONVERT(date, '20220503'), 50),
   (CONVERT(date, '20220514'), 250),
   (CONVERT(date, '20220515'), 0)
) v (dt, amt)

声明:

SELECT 
   dt, 
   amt,
   AVG(amt) OVER (ORDER BY dt ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) AS running_avg,
   CASE WHEN COUNT(*) OVER (ORDER BY dt ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) = 3 
      THEN AVG(amt) OVER (ORDER BY dt ROWS BETWEEN 2 PRECEDING AND CURRENT ROW)
      ELSE 0
   END AS running_avg2
FROM trans
ORDER BY dt

结果:

dt amt running_avg running_avg2
2022-05-01 100 100 0
2022-05-02 150 125 0
2022-05-03 50 100 100
2022-05-14 250 150 150
2022-05-15 0 100 100