我正在尝试计算SQL Server 2008中我的数据的移动平均值,但我找到的唯一方法是使用@variable。例如,我有这组数据:
StudyDate Cpty Value ---------- ---- ---------------------- 2015-11-24 1 3009 2015-11-24 2 2114 2015-11-24 3 558 2015-11-24 4 121 2015-11-24 5 2515 2015-11-24 6 81 2015-11-24 7 80 2015-11-24 8 1534 2015-11-24 9 136 2015-11-24 10 5674 2015-11-25 1 2731 2015-11-25 2 2197 2015-11-25 3 550 2015-11-25 4 124 2015-11-25 5 2532 2015-11-25 6 81 2015-11-25 7 80 2015-11-25 8 1700 2015-11-25 9 122 2015-11-25 10 5788 2015-11-26 1 2666 2015-11-26 2 2175 2015-11-26 3 408 2015-11-26 4 124 2015-11-26 5 2545 2015-11-26 6 81 2015-11-26 7 81 2015-11-26 8 1712 2015-11-26 9 122 2015-11-26 10 5967
我想找到每天的移动平均线。如果我运行此查询:
DECLARE @StudyDate DATE = '2015-11-26'
SELECT @StudyDate,
Cpty,
AVG(Value)
FROM #MovAvg
WHERE StudyDate > DATEADD(m,-1,@StudyDate) AND StudyDate <= @StudyDate
GROUP BY Cpty
ORDER BY Cpty
然后我得到2015-11-26只有一天的平均值,但是我可以得到每个Cpty每天的平均值吗?
提前谢谢!
答案 0 :(得分:2)
在SQL Server 2008中,您可以使用outer apply
执行此操作。我不确定你的“移动平均线”是什么意思,但它似乎是上个月的平均值。
所以:
select t.*, tavg.value
from t outer apply
(select avg(t2.value) as value
from t t2
where t2.cpty = t.cpty and
t2.studydate > DATEADD(month, -1, t.StudyDate) and
t2.StudyDate <= t.StudyDate
) tavg;