小编典典

甲骨文移动平均线

sql

我有一个表(日期,有效负载),其中包含约10年的数据,我想基于14天(2周)和90天(12周)的间隔计算移动平均值(MA),以显示有效负载的趋势

我已经写了这个查询,但是它得到了错误的值

SELECT x.*,
  ABS (LTMA-STMA) DIFFERECNE
FROM
  (SELECT SDATE,
    PAYLOAD,
    AVG(PAYLOAD) OVER (ORDER BY W ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) STMA,
    AVG(PAYLOAD) OVER (ORDER BY W ROWS BETWEEN 12 PRECEDING AND CURRENT ROW) LTMA
  FROM
(SELECT b.*,
  TO_NUMBER(TO_CHAR( X.SDATE, 'W')) W
FROM
  (SELECT TO_DATE(TO_CHAR(a.SDATE, 'YYYY-MM-DD'), 'YYYY-MM-DD') SDATE,
    SUM(a.PAYLOAD) PAYLOAD
  FROM TABLE_PAYLOAD a
  WHERE a.SDATE  > sysdate - 3 * 365      
  GROUP BY TO_CHAR(a.SDATE, 'YYYY-MM-DD')
  ORDER BY TO_CHAR(a.SDATE, 'YYYY-MM-DD')
  ) b    )
 ORDER BY SDATE
 ) x;

实际上我知道是什么MA,但我不了解Oracle的工作原理!

我可以MA在Excel中进行计算,但是我需要在数据库级别执行此操作,能否请您告诉我如何执行此操作?


阅读 169

收藏
2021-04-28

共1个答案

小编典典

我不明白使用的目的是TO_CHAR(SDATE, 'W')什么?根据文档,这应该为您提供当月的星期数…

无论如何,我试图简化查询,希望它仍然可以满足您的需求:

SELECT x.*, ABS (LTMA-STMA) DIFFERENCE
FROM
(
  SELECT SDATE, PAYLOAD,
         AVG(PAYLOAD) OVER (ORDER BY SDATE rows BETWEEN 14 PRECEDING AND CURRENT ROW) STMA,
         AVG(PAYLOAD) OVER (ORDER BY SDATE rows BETWEEN 90 PRECEDING AND CURRENT ROW) LTMA
  FROM
  (
    SELECT a.SDATE, SUM(a.PAYLOAD) PAYLOAD
    FROM TABLE_PAYLOAD a
    WHERE a.SDATE  > sysdate - 3 * 365      
    GROUP BY a.SDATE
  )
) x
ORDER BY SDATE;

PS:这样做我也看不到要点TO_DATE(TO_CHAR(a.SDATE, 'YYYY-MM-DD'), 'YYYY-MM-DD'),这相当于a.SDATE

2021-04-28