php - Calculate the 5-day moving average - Set value to 0 if there is a gap between dates. -
i'm trying calculate 5-day moving average. , works fine, except when there gap between dates. when there gap, value missing date(-s) should set 0 show correct moving average.
here table (orders_total) , can see there no date 1/7/13 , causing problem:
orders_id value date 1 199 1/1/13 0:00 2 199 1/2/13 0:00 3 199 1/3/13 0:00 4 199 1/4/13 0:00 5 249 1/5/13 0:00 6 199 1/6/13 0:00 7 199 1/8/13 0:00 8 199 1/9/13 0:00 9 199 1/10/13 0:00 10 199 1/11/13 0:00 11 199 1/12/13 0:00 12 199 1/13/13 0:00 if value missing date 1/7/13 set zero, correct 5-day moving average (that 'm looking for) is:
199 199 199 199 209 209 169.2 169.2 169.2 159.2 159.2 199 199 this code i'm using, , not showing correct moving average when there gap between dates:
select ot1.value, ot1.date, (select sum(ot2.value) / count(ot2.value) orders_total ot2 datediff(ot1.date, ot2.date) between 0 , 4) '5daymovingavg' orders_total ot1 order ot1.date";
if know 5 days, why divide count(ot2.value)? unless you're trying handle edge cases, in case, handle edge cases differently normal case.
Comments
Post a Comment