0

以下视图应该计算Total 和 Amount 之间的差异。但是如果在 bill_pay_allocations 中没有输入相应的付款,则视图计算失败。即使没有相应的付款,我如何计算差额?

SELECT
`alphabase`.`bill_ing_sheets`.`INVOICE_NO` AS `INVOICE_NO`,
`alphabase`.`bill_ing_sheets`.`TOTAL` AS `TOTAL`,
`alphabase`.`bill_pay_allocations`.`AMOUNT` AS `AMOUNT`,
`alphabase`.`bill_pay_allocations`.`AMOUNT` - `alphabase`.`bill_ing_sheets`.`TOTAL` AS `Difference` 
FROM
`alphabase`.`bill_ing_sheets` left join `alphabase`.`bill_pay_allocations` 
ON
`alphabase`.`bill_pay_allocations`.`BILLING_ID` = `alphabase`.`bill_ing_sheets`.`BILLING_ID` 
left join `alphabase`.`bill_payments` 
ON
`alphabase`.`bill_payments`.`PAYMENT_ID` = `alphabase`.`bill_pay_allocations`.`PAYMENT_ID`
4

1 回答 1

0

您应该在 bill_ing_sheets 和 bill_pay_allocations 之间使用 LEFT OUTER JOIN。使用 Case 语句在 Amount 中查找 Null 值并将其替换为 0。

如果在 bill_payments 上需要,也传播 LEFT OUTER JOIN。

请看下面的代码。

SELECT
`alphabase`.`bill_ing_sheets`.`INVOICE_NO` AS `INVOICE_NO`,
`alphabase`.`bill_ing_sheets`.`TOTAL` AS `TOTAL`,
(case when `alphabase`.`bill_pay_allocations`.`AMOUNT` is not null then `alphabase`.`bill_pay_allocations`.`AMOUNT` else 0 end) AS `AMOUNT`,
(case when `alphabase`.`bill_pay_allocations`.`AMOUNT` is not null then `alphabase`.`bill_pay_allocations`.`AMOUNT` else 0 end) - `alphabase`.`bill_ing_sheets`.`TOTAL` AS `Difference` 
FROM
`alphabase`.`bill_ing_sheets` left outer join `alphabase`.`bill_pay_allocations` 
ON
`alphabase`.`bill_pay_allocations`.`BILLING_ID` = `alphabase`.`bill_ing_sheets`.`BILLING_ID` 
left outer join `alphabase`.`bill_payments` 
ON
`alphabase`.`bill_payments`.`PAYMENT_ID` = `alphabase`.`bill_pay_allocations`.`PAYMENT_ID`
于 2013-06-04T22:42:29.913 回答