oracle last_value函数和预测

时间:2015-04-21 13:33:18

标签: sql oracle oracle11g forecasting

我需要返回一个结果集,其中包含我的合同,项目表中最后一个日期的最后一个值;稍后我将需要使用此结果集来预测我预测的剩余月份的值。 我似乎没有到达任何地方,我需要采取每个项目的最后日期,价值对&合同并预测它。 我只走了第一部分,即提取最后的日期,价值;还需要第二部分的帮助,即采取这种结果并进行预测。 我们走了:

我的桌子

contrato,projeto,data,valor
C001    P1  01-APR-15   10
C001    P1  01-APR-15   10
C001    P1  01-MAY-15   15
C001    P2  01-MAY-15   19
C001    P2  01-JUN-15   21
C002    P1  01-JUL-15   19
C002    P2  01-AUG-15   19

我的查询

select CONTRATO,PROJETO,FCST,
LAST_VALUE("PERIODO" IGNORE NULLS)OVER (PARTITION BY contrato,projeto,FCST,periodo   ORDER BY contrato,projeto,FCST RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)LAST_DATE
from(
select CONTRATO,PROJETO,periodo,
  LAST_VALUE("VALOR" IGNORE NULLS)OVER (PARTITION BY contrato,projeto,periodo,valor ORDER BY PERIODO,contrato,projeto RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING )FCST
  FROM "HYP_STAGE"."INVENT_TABLE_FCST"
  )ORDER BY CONTRATO,PROJETO,PERIODO;

我的结果集,正在重复月份的值,每月只需要一个值;

C001    P1  10  01-APR-15
C001    P1  10  01-APR-15
C001    P1  15  01-MAY-15
C001    P2  19  01-MAY-15
C001    P2  21  01-JUN-15
C002    P1  19  01-JUL-15
C002    P2  19  01-AUG-15

非常感谢!

1 个答案:

答案 0 :(得分:0)

这是您可能需要的查询:

SQLFiddle demo

select distinct contrato, projeto, 
    last_value(periodo) over (partition by contrato, projeto 
      order by periodo nulls first 
      rows between unbounded preceding and unbounded following) p,
    last_value(valor) over (partition by contrato, projeto 
      order by periodo nulls first 
      rows between unbounded preceding and unbounded following) v
  from INVENT_TABLE_FCST order by contrato, projeto

关于预测未来期间结果的问题的第二部分,您没有通过预测结果解释您的意思。


  

如果我有更多变量,如细分,产品如何查询?

我怀疑细分和产品的处理方式应与contrato和projecto相同,因此您需要将这些列添加到select ...部分和partition by...部分。

但您可能希望以类似valor的方式对待它们,这取决于您的需求。

  

第二部分,需要提前48个月预测上个月的值(填写相同的值)

为此,我们需要一些生成新句点的分层查询,在这里我使用了recursive CTE

with data(n, contrato, projeto, periodo, valor) as (
  select distinct 1, contrato, projeto,
      last_value(periodo) over (partition by contrato, projeto
        order by periodo nulls first 
        rows between unbounded preceding and unbounded following) periodo,
      last_value(valor) over (partition by contrato, projeto
        order by periodo nulls first 
        rows between unbounded preceding and unbounded following) valor
    from INVENT_TABLE_FCST  
  union all
  select n+1, contrato, projeto, add_months(periodo, 1), valor
    from data where n<48 )
select contrato, projeto, periodo, valor 
  from data order by contrato, projeto, periodo
  

完美!它运作得很好!

那么为什么不将答案标记为已接受? ; - )


还有一点需要注意:如果你的表中有任何主键,那将是非常好的,所以我们有不同的增量 使分区和排序正确的值。