2013-07-16 77 views
0

DB2表ZB_BILL_ERR:如何更新Db2表格行並刪除現有行?

PROCESS_DATE CURR_PROCESS_DT ACCOUNT_NUMBER SEQ_NUM ERROR_REASON 
07/14/2013 07/14/2013 A123456789 1  Trancode Invalid 
07/15/2013 07/15/2013 B987654321 1  Adjustment code invalid 
07/16/2013 07/16/2013 A123456789 2  Multi Single ind invalid 

預期輸出:

PROCESS_DATE CURR_PROCESS_DT ACCOUNT_NUMBER SEQ_NUM ERROR_REASON 
07/15/2013 07/15/2013 B987654321 1  Adjustment code invalid 
07/14/2013 07/16/2013 A123456789 2  Multi Single ind invalid 

的A123456789的最新行的過程日期將在表中的賬戶最古老的工藝至今,在這種情況下,這是2013年7月14日和刪除A123456789

+0

......我會通過使表開始(如果可能的話)(每個ID只需要一行),然後在過程中更新或插入,或者使用MERGE語句(如果您的DB2版本支持它),則在A123456789上是唯一的。什麼版本的DB2,到目前爲止您嘗試過什麼? –

回答

0

最古老的行識別最新的記錄,使用

row_number() over (partition by account_number 
        order by curr_processs_dt descending 
        ) as aging 

它將按帳戶內的降序排列您的行。選擇age = 1的行以獲取最近的行。

要得到的最早日期爲一筆賬:

select account_number, min(process_dt) as first_processed 
    from input 
    group by account_number 

因此,讓我們把這個連成一片(有點複雜)的SQL語句

MERGE into ZB_BILL_ERR m 
USING ( 
     with g as 
     (
      select account_number 
       , min(process_dt) as first_processed 
      from ZB_BILL_ERR 
      group by account_number 
     ) 
     select i.* 
      , row_number() over (partition by account_number 
            order by curr_processs_dt descending 
            ) as aging 
      , first_processed 
      from g 
      join ZB_BILL_ERR i on i.account_number = g.account_number 
    ) as x 
    ON m.account_number = x.accout_number 
    WHEN MATCHED and x.aging = 1 THEN 
    UPDATE process_dt = x.first_processed 
    WHEN MATCHED and x.aging > 1 THEN 
    DELETE 
;