在SQL-server数据库中我想用table2的值更新table1,我有两个表pay_tbl和bill_tbl。这两个属性具有以下属性。
pay_tbl
pay_ID type int -->pk
outstanding_amount type int
bill_tbl
pay_ID type int --> Fk
amount_to_Pay type int
amount_paid type int
paid_date type date
bill_status type varchar
我想通过添加table2的amount_to_pay列的值来更新pay_tbl的outstanding_amount列
(outstanding_payment+=amount_to_pay)
但只是更新帐单状态为“未付款”的帐户。和日期是相对于当月的上个月,即:现在月份是2月,然后只更新日期为1月的表格。我尝试了以下查询,但我知道这是错误的
UPDATE pay_tbl
SET
outstanding_payment = outstanding_Payment +
(SELECT
amount_to_pay
FROM bill_tbl INNER JOIN bill_tbl ON
bill_tbl.pay_ID = pay_tbl.payID )
WHERE
MONTH(Date) = DATEPART(MONTH, DATEADD(MONTH, -1, [Date]))
AND YEAR(Date) = DATEPART(YEAR, DATEADD(MONTH, -1, [Date]))
答案 0 :(得分:0)
UPDATE
TABLE_A
SET
TABLE_A.OUTSTANDING_PAYMENT = TABLE_A.OUTSTANDING_PAYMENT+TABLE_B.AMOUNT_TO_PAY
FROM
PAY_TBL AS TABLE_A
INNER JOIN (SELECT SUM(AMOUNT_TO_PAY) AMOUNT_TO_PAY ,PAY_ID FROM BILL_TBL WHERE MONTH(DATE) = DATEPART(MONTH, DATEADD(MONTH, -1, [DATE]))
AND YEAR(DATE) = DATEPART(YEAR, DATEADD(MONTH, -1, [DATE]))
AND BILL_STATUS='NO PAID'
GROUP BY PAY_ID) AS TABLE_B
ON TABLE_A.PAY_ID = TABLE_B.PAY_ID