2015-04-21 71 views
0

我需要從我的合同項目表中返回最後一個日期值的結果集;稍後我將需要使用此結果集來預測我預測的剩餘月份的值。 我似乎沒有得到任何地方,我需要採取最後的日期,價值對每個項目&合同和項目。 我只是走了第一部分,這是提取最後的日期,價值;對於第二部分也需要幫助,第二部分是採取這個結果並對其進行預測。 這裏,我們去:oracle last_value函數和預測

我的表

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 

非常感謝!

回答

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 

你對投影未來期間的結果問題的第二部分,你不解釋一下你的預測結果是什麼意思。


如果我有更象細分變量,產品如何wpuld查詢呢?

我懷疑段和產品應的處理方式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 

完美!它效果很好!

那麼爲什麼不把答案標記爲接受? ;-)


還要說明一點:這將是非常好的,如果你有在你的表中的任何主鍵,所以我們有不同的,增加 值,這使得劃分和排序正確的肯定。

+0

完美!它效果很好! – user1766419

+0

很高興幫助。請閱讀此短文[文章](http://stackoverflow.com/help/someone-answers);-) –

+0

它的工作完美。如果我有更多的變量像段,產品如何wpuld查詢是?第二部分,需要提前48個月預測上個月的價值(填寫相同的值)。非常感謝! – user1766419