建表以下( 歷史拉鍊表):spa
新表(每日更新的):code
實現語句:blog
MERGE INTO test_target t1 USING ( SELECT nvl(c.id, b.id) AS id ,CASE WHEN c.endtime = to_date('9999-12-30', 'yyyy-mm-dd') AND b.id IS NULL THEN c.STATUS WHEN c.id IS NULL THEN b.STATUS END AS STATUS ,CASE WHEN c.endtime = to_date('9999-12-30', 'yyyy-mm-dd') AND b.id IS NULL THEN c.begain WHEN c.id IS NULL THEN to_date('2017-03-15', 'yyyy-mm-dd') END AS begain ,CASE WHEN c.endtime = to_date('9999-12-30', 'yyyy-mm-dd') AND b.id IS NULL THEN to_date('2017-03-15', 'yyyy-mm-dd') WHEN c.id IS NULL THEN to_date('9999-12-30', 'yyyy-mm-dd') END AS endtime FROM test_b b FULL JOIN test_target c ON b.id = c.id AND b.STATUS = c.STATUS WHERE c.id IS NULL OR ( c.endtime = to_date('9999-12-30', 'yyyy-mm-dd') AND b.id IS NULL ) ) t2 ON ( t1.id = t2.id AND t1.STATUS = t2.STATUS ) WHEN MATCHED THEN UPDATE SET t1.endtime = t2.endtime WHERE t1.endtime = to_date('9999-12-30', 'yyyy-mm-dd') WHEN NOT MATCHED THEN INSERT VALUES ( t2.id ,t2.STATUS ,t2.begain ,t2.endtime );
結果以下:get