我正努力制作适用于以下数据的更新脚本:
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"具有基于不同标准的数字的字段:
所需的输出应为:
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,但在不匹配时无法更新。
提前致谢!
答案 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;