根据表2中的标准更新表1中的字段? ORACLE

时间:2017-10-12 18:28:33

标签: oracle sql-update oracle-sqldeveloper

我正努力制作适用于以下数据的更新脚本:

TOWER_PAYMENT TABLE                                         
============================================================== 
PAY_PERIOD|TOWER_ID|APARTMENT_NUM|MONTH_PAYMENT|PAYMENT_STATUS     
201703    |10      |101          |700          |NULL
201704    |10      |101          |700          |NULL
201703    |10      |102          |700          |NULL
201704    |10      |102          |700          |NULL                  
201703    |20      |101          |800          |NULL     
201704    |20      |101          |800          |NULL               
201703    |20      |102          |800          |NULL     
201704    |20      |102          |800          |NULL              

PAYMENT_STATUS TABLE
==============================================
PAY_PERIOD|TOWER_ID|APARTMENT_NUM|PAYMENT_DONE
201703    |10      |101          |700 
201704    |10      |101          |400 
201703    |10      |102          |500
201704    |10      |102          |700 
201703    |20      |101          |800 

我希望更新" PAYMENT_STATUS"具有基于不同标准的数字的字段:

  • 如果是" APARTMENT_NUM"属于" TOWER_ID"可以在" PAYMENT_STATUS"用于匹配" PAY_PERIOD"的表格,然后更新" PAYMENT_STATUS"字段为1。
  • 如果" APARTMENT_NUM"属于" TOWER_ID的" PAYMENT_STATUS"用于匹配" PAY_PERIOD"的表格,然后更新" PAYMENT_STATUS"字段为2.
  • 如果" APARTMENT_NUM"有一个" PAYMENT_DONE"小于" MONTH_PAYMENT",然后更新" PAYMENT_STATUS"字段为3.

所需的输出应为:

TOWER_PAYMENT
====================================================================     
PAY_PERIOD|TOWER_ID|APARTMENT_NUM|MONTH_PAYMENT|PAYMENT_STATUS     
201703    |10      |101          |700          |1
201704    |10      |101          |700          |3
201703    |10      |102          |700          |3
201704    |10      |102          |700          |1                  
201703    |20      |101          |800          |1     
201704    |20      |101          |800          |2               
201703    |20      |102          |800          |2     
201704    |20      |102          |800          |2            

我已尝试使用MERGE INTO,但在不匹配时无法更新。

提前致谢!

1 个答案:

答案 0 :(得分:2)

UPDATE tower_payment
   SET payment_status   = CASE
                              WHEN (SELECT payment_done
                                      FROM payment_status
                                     WHERE tower_payment.apartment_num = payment_status.apartment_num) < month_payment
                              THEN
                                  3
                              WHEN (SELECT payment_done
                                      FROM payment_status
                                     WHERE tower_payment.apartment_num = payment_status.apartment_num)
                                       IS NULL
                              THEN
                                  2
                              ELSE
                                  1
                          END;