即使没有儿童记录,也需要查看计算差异

时间:2013-06-04 21:42:59

标签: mysql

以下视图应该计算Total&之间的差异量。但是如果在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`

1 个答案:

答案 0 :(得分: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`