2015-06-09 85 views
0

我有兩個表t1t2基於匹配/不匹配的表更新

t1具有這樣的結構:

yearmonth 
account 
company 
RCV_amount_t1 

t2具有這樣的結構:

yearmonth 
account 
company 
billing amount 
billing amount CM_1 
billing amount CM_2 
RCV_amount_t2 

我想加入使用yearmonthaccount,並且companyt2t1。如果它們匹配,我想用RCG_amount_t1中的值更新RCV_amount_t2。否則,我想將RCV_amount_t2設置爲空格。

以同樣的方式,我想加入t1使用yearmonthaccount,並且company並設置相應值t2

是否有可能實現?如果是這樣,我該怎麼辦?

+0

我對句子「以相同的方式......」感到困惑。如果你首先用T1中的值匹配T2中的所有行,那麼匹配的時候會做什麼? –

回答

0

你會想要使用MERGE
它允許您連接兩個表並指定如何更新值(如果它們匹配)。

一個MERGE語句的一般結構如下:

MERGE INTO driver_table 
USING other_table 
ON 
(
    driver_table.column1 = other_table.column1 
AND driver_table.column2 = other_table.column2 
AND ... 
) 
WHEN MATCHED THEN UPDATE 
    SET 
     driver_table.some_column = other_table.some_value, 
     driver_table.some_flag = 'Y', 
     ... 
; 
+0

但是,問題指出「如果沒有匹配,我想將RCV_amount_t2設置爲空格。」我不相信MERGE會支持這一點。 –

+0

@DaveCosta - 它不會。您可能首先將所有* RCV_amount_t2值清空,然後更新匹配的值。它會有同樣的效果。 –

1

我想加盟T2使用yearmonth,帳戶和公司爲t1。如果他們 匹配,我想用RCG_amount_t1中的值更新RCV_amount_t2。 否則,我想將RCV_amount_t2設置爲空格。

這將更新匹配的行,並更新與NULL不匹配的行。如果該字段是數字,則不能將其更新爲「空格」; NULL將是沒有價值的適當指標。如果該字段不是數字,那麼您可以進行第二次更新,以用您喜歡的任何值代替NULL值,但NULL在我看來似乎仍然是沒有任何價值的最合適的指標。

UPDATE t2 SET rcv_amount_t2 = (
    SELECT rcv_amount_t1 
    FROM t1 
    WHERE t1.yearmonth = t2.yearmonth 
    AND t1.account = t2.account 
    AND t1.company = t2.company 
) 
0

看來,我們不能在一個查詢中解決這個問題,我們需要一個mergecorrelated query,它正常工作對我來說:

匹配時,這將更新T2與T1值:

MERGE INTO t2 
    USING (SELECT yearmonth, account, company, RCV_amount_t1 FROM t1) S 
    ON (t1.yearmonth = t2.yearmonth and 
     t1.account = t2.account and 
     t1.company = t2.company) 
    WHEN MATCHED THEN UPDATE SET t2.RCV_amount_t2 = S.RCV_amount_t1; 

然後,當不匹配的查詢方含一個corrolated子查詢爲空:

update t2 set RCV_amount_t2 = ' ' where yearmonth||account||company not in(
select yearmonth||account||company from t1 
where t1.yearmonth = t2.yearmonth and t1.account=t2.account and t1.company=t2.company);