Oracle移动平均线

时间:2014-03-04 08:25:18

标签: sql oracle

我有一个表(日期,有效载荷),其中包含大约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是如何工作的!

我可以在Excel中计算MA,但我需要在数据库级别执行此操作,请您告诉我该怎么做?

1 个答案:

答案 0 :(得分:3)

我不明白使用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 ......