sql server - How to create a multiple variable in SQL? -
i trying calculate a, sort of, moving average data in sql server 2008, way have found using @variable. example have set of data:
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
and want find moving average every day. if run query:
declare @studydate date = '2015-11-26' select @studydate, cpty, avg(value) #movavg studydate > dateadd(m,-1,@studydate) , studydate <= @studydate group cpty order cpty
then average 1 day '2015-11-26', can average every day every cpty?
thank in advance!
in sql server 2008, using outer apply
. i'm not sure mean "moving average", appears average previous month.
so:
select t.*, tavg.value t outer apply (select avg(t2.value) value t t2 t2.cpty = t.cpty , t2.studydate > dateadd(month, -1, t.studydate) , t2.studydate <= t.studydate ) tavg;
Comments
Post a Comment