繁体   English   中英

MySQL:同一查询中有两个移动平均线?

[英]MySQL: Two moving averages in the same query?

是否有可能同时从同一个MySQL数据集中获得两个不同的移动平均线?

我正在尝试从MySQL数据库中提取数据,该数据库为我提供“原始”数据,以及相同数据集的两个不同移动平均值。 我最好的尝试是在下面,问题是两个移动平均线似乎产生相同的结果?

此外,是否有更有效的查询数据方式? 数据集相当大,这个查询需要花费太长时间才能运行?

SELECT
  t1.`DateTime`,

  t1.`Positive` AS `RawData`,

(SELECT AVG(t2.`Positive`)
 FROM `tbl_DATA_KeywordResults` as t2
WHERE t2.`DateTime` <= t1.`DateTime`
ORDER BY t2.`DateTime` DESC
LIMIT 96
)  AS `DailyAverage`,

(SELECT AVG(t3.`Positive`)
FROM `tbl_DATA_KeywordResults` as t3
WHERE t3.`DateTime` <= t1.`DateTime`
ORDER BY t3.`DateTime` DESC
LIMIT 674
)  AS `WeeklyAverage`

FROM `tbl_DATA_KeywordResults` AS t1
ORDER BY t1.`DateTime`;

达到平均值后,您将获得限制。 子查询的正确形式是:

(select avg(Positive)
 from (SELECT t2.`Positive`
       FROM `tbl_DATA_KeywordResults` as t2
       WHERE t2.`DateTime` <= t1.`DateTime`
       ORDER BY t2.`DateTime` DESC
       LIMIT 96
      ) t
)  AS `DailyAverage`

我不是100%肯定这将作为子查询工作。 我相信MySQL将外部引用( where子句中的内容)限制为一层深层。

在MySQL中有更多痛苦的方法:

select t1.DateTime, t1.RawData,
       avg(case when t2.DateTime between avg_96_dt and t1.DateTime then t2.Positive end) as avg96,
       avg(case when t2.DateTime between avg_674_dt and t1.DateTime then t2.Positive end) as avg674
from (SELECT t1.`DateTime`, t1.`Positive` AS `RawData`,
             (SELECT t2.DateTime
              FROM `tbl_DATA_KeywordResults` t2
              WHERE t2.`DateTime` <= t1.`DateTime`
              ORDER BY t2.`DateTime` DESC
              LIMIT 95, 1
             )  as avg_96_dt,
             (SELECT t2.DateTime
              FROM `tbl_DATA_KeywordResults` t2
              WHERE t2.`DateTime` <= t1.`DateTime`
              ORDER BY t2.`DateTime` DESC
              LIMIT 673, 1
             ) as avg_674_dt
      FROM `tbl_DATA_KeywordResults` t1
     ) t1 join
     tbl_DATA_KeywordResults t2
group by t1.DateTime, t1.RawData
ORDER BY t1.`DateTime`;

也就是说,获取日期时间范围的限制,然后在不同的步骤中进行平均。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM