我有这样的事情:
id | value
---------------
201311 | 10
201312 | 15
201401 | 20
201402 | 5
201403 | 17
我需要这样的结果:
201311 | NULL or 0
201312 | 3.3 // 10/3
201401 | 8.3 // (15+10)/3
201402 | 15 // (20+15+10)/3
201403 | 13.3 // (5+20+15)/3
到目前为止,我已经到了能够获得前三行的AVG的地步:
select AVG(c.value) FROM (select b.value from table as b where b.id < 201401 order by b.id DESC LIMIT 3) as c
手动传递id。我无法为每个ID执行此操作。
任何想法都会非常感激!
非常感谢。
问候
答案 0 :(得分:0)
我认为您必须编写存储过程,使用游标,遍历表并使用游标循环中计算的值填充新表。如果您需要帮助写出光标循环,只需删除注释,我就可以给您一个例子。
答案 1 :(得分:0)
我现在接受了这个:
SELECT a.id, (select AVG(b.value) FROM table as b where b.id < a.id AND str_to_date(CONCAT(b.id,'01'), '%Y%m%d') >= DATE_SUB(str_to_date(CONCAT(a.id,'01'), '%Y%m%d'), INTERVAL 3 MONTH)) FROM `table` as a WHERE 1
但我确信应该有一个更好/更清洁的解决方案
答案 2 :(得分:0)
select a.id,coalesce(b.value,0) from test a left outer join
(select a.id, sum(b.value)/3 as value from
(select @row:=@row+1 as rownum,id,value from test,(select @row:=0)r) a,
(select @row1:=@row1+1 as rownum,id,value from test,(select @row1:=0)r) b
where b.rownum in (a.rownum-1,a.rownum-2,a.rownum-3)
group by a.rownum) b
on a.id=b.id;