简体   繁体   English

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

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

Is it possible to get two different moving averages from the same MySQL dataset at the same time? 是否有可能同时从同一个MySQL数据集中获得两个不同的移动平均线?

I'm trying to extract data from a MySQL database that gives me the 'raw' data, plus two different moving averages of the same data set. 我正在尝试从MySQL数据库中提取数据,该数据库为我提供“原始”数据,以及相同数据集的两个不同移动平均值。 My best attempt is below, the problem is that the two moving averages appear to be producing identical results? 我最好的尝试是在下面,问题是两个移动平均线似乎产生相同的结果?

Also, is there a more efficient way of querying the data? 此外,是否有更有效的查询数据方式? The dataset is reasonably large and this query takes a little too long to run? 数据集相当大,这个查询需要花费太长时间才能运行?

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`;

You are taking the limit after you do the average. 达到平均值后,您将获得限制。 The correct form of the subquery would be: 子查询的正确形式是:

(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`

I'm not 100% sure that this will work as a subquery. 我不是100%肯定这将作为子查询工作。 I believe MySQL limits outer references (what's in the where clause) to one layer deep. 我相信MySQL将外部引用( where子句中的内容)限制为一层深层。

There are more painful ways of doing this in MySQL: 在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`;

That is, get the limits for the date time range and then do the average in a different step. 也就是说,获取日期时间范围的限制,然后在不同的步骤中进行平均。

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

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