2015-06-01 22 views
2

我有一個產品銷售源數據如下。Oracle SQL:參考最後記錄的表達式輸出

Product  SalesDate 

ProductA 28-Apr-2015 
ProductA 28-Apr-2015 
ProductA 30-Apr-2015 
ProductA 30-Apr-2015 
ProductA 30-Apr-2015 
ProductA 30-Apr-2015 

使用LAG功能獲得上一個銷售日期。

Product  SalesDate  PrevDate 
ProductA 28-Apr-2015  28-Apr-2015 
ProductA 28-Apr-2015  28-Apr-2015 
ProductA 30-Apr-2015  28-Apr-2015 
ProductA 30-Apr-2015  30-Apr-2015 
ProductA 30-Apr-2015  30-Apr-2015 
ProductA 30-Apr-2015  30-Apr-2015 

使用以下邏輯來創建新日期。

CASE WHEN Sales Date - Prev Sales Date <= 10 days THEN Prev Sales Date 
ELSE Sales Date 
END as New date 

輸出我是

Product  SalesDate  PrevDate  NewDate 
ProductA 28-Apr-2015  28-Apr-2015  28-Apr-2015 
ProductA 28-Apr-2015  28-Apr-2015  28-Apr-2015 
ProductA 30-Apr-2015  28-Apr-2015  28-Apr-2015 
ProductA 30-Apr-2015  30-Apr-2015  30-Apr-2015 
ProductA 30-Apr-2015  30-Apr-2015  30-Apr-2015 
ProductA 30-Apr-2015  30-Apr-2015  30-Apr-2015 

這裏是棘手的部分。我期待最後3行的新日期爲2015年4月28日。爲了達到這個目的,每行中的LAG函數應該引用前一行的新日期。

這意味着你必須引用新的日期(其計算表達式)從上一行。

所需的輸出如下所示。

Product  SalesDate  PrevDate  NewDate 
ProductA 28-Apr-2015  28-Apr-2015  28-Apr-2015 
ProductA 28-Apr-2015  28-Apr-2015  28-Apr-2015 
ProductA 30-Apr-2015  28-Apr-2015  28-Apr-2015 
ProductA 30-Apr-2015  30-Apr-2015  28-Apr-2015 
ProductA 30-Apr-2015  30-Apr-2015  28-Apr-2015 
ProductA 30-Apr-2015  30-Apr-2015  28-Apr-2015 

任何幫助將不勝感激。非常感謝。

回答

0

如果Oracle版本至少11g中,你可以使用這個recursive查詢:

with t as (
    select product, salesdate, 
     row_number() over (partition by product order by salesdate) rn 
    from products), 
r(rn, product, salesdate, newdate) as (
    select rn, product, salesdate, salesdate newdate from t where rn = 1 
    union all 
    select t.rn, t.product, t.salesdate, 
     case when t.salesdate - r.newdate <= 10 then r.newdate else t.salesdate end 
    from r join t on r.product = t.product and r.rn + 1 = t.rn) 
select * from r 

SQLFiddle demo

我演示增加了兩個排,檢查日期的差異狀況。