如何计算MySQL中的多个移动平均线

时间:2011-08-14 21:03:26

标签: mysql

使用下表,如何获得5期移动平均线,10期移动平均线,5期指数移动平均线的列。

+--------+------------+
| price  | data_date  |
+--------+------------+
| 122.29 | 2009-10-08 |
| 122.78 | 2009-10-07 |
| 121.35 | 2009-10-06 |
| 119.75 | 2009-10-05 |
| 119.02 | 2009-10-02 |
| 117.90 | 2009-10-01 |
| 119.61 | 2009-09-30 |
| 118.81 | 2009-09-29 |
| 119.33 | 2009-09-28 |
| 121.08 | 2009-09-25 |
+--------+------------+

3 个答案:

答案 0 :(得分:2)

示例中的5行移动平均线不起作用。 LIMIT运算符适用于返回集,而不是聚合中考虑的行,因此更改它对聚合值没有影响。

答案 1 :(得分:0)

SELECT AVG(a.price) FROM (SELECT price FROM t1 WHERE data_date <= ? ORDER BY data_date DESC LIMIT 5) AS a;

替换?与你需要MA的日期。

答案 2 :(得分:0)

select t1.*
from (
select p.*, count(p.id), 
COUNT(1) filter(where t.id in (2,3)) ranking
from plainto_tsquery('hElLo') AS q , post p 
left join post_tag pt on pt.post_id = p.id
left join tag t on t.id = pt.tag_id
WHERE (tsv @@ q) or t.id in (2,3)
group by p.id
) as t1 
order by count desc, ranking asc, ts_rank_cd(t1.tsv, plainto_tsquery('hElLo')) desc 
limit 5;

为10天MA更改6到13