簡體   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