之前已经部分回答了这个问题,但我想补充一个问题。我从这里得到的代码正在运行,但我想得到唯一有iif的记录(TblLoan.FutureValue为null,0,TblLoan.FutureValue) - iif(Payment.TotalPaid为null,0,Payment.TotalPaid)= 0或更少。换句话说,只有0或更少余额的记录。
SELECT TblLoan.LoanID, TblCustomer.LastName, Payment.TotalPaid AS Payments, iif(TblLoan.FutureValue is null, 0, TblLoan.FutureValue) -
iif(Payment.TotalPaid is null, 0, Payment.TotalPaid) AS Balance
FROM (TblLoan LEFT JOIN (SELECT LoanID, sum(TotalAmount) as TotalPaid
FROM TblPayment group by LoanID
) AS Payment ON Payment.LoanID = TblLoan.LoanID) LEFT JOIN TblCustomer ON TblLoan.CustomerID = TblCustomer.CustID;
我知道应该有一个where子句但是我无法弄清楚放置WHERE Balance =<语句末尾的0似乎不起作用。
谢谢。
答案 0 :(得分:1)
您应该在where
子句中重复使用表达式本身,而不是别名“Balance”。请注意,您可以在此使用Nz
function代替iif
:
SELECT TblLoan.LoanID,
TblCustomer.LastName,
Payment.TotalPaid AS Payments,
Nz(TblLoan.FutureValue) - Nz(Payment.TotalPaid) AS Balance
FROM TblLoan
LEFT JOIN (
SELECT LoanID,
sum(TotalAmount) as TotalPaid
FROM TblPayment group by LoanID
) AS Payment
ON Payment.LoanID = TblLoan.LoanID
LEFT JOIN TblCustomer ON TblLoan.CustomerID = TblCustomer.CustID
WHERE Nz(TblLoan.FutureValue) - Nz(Payment.TotalPaid) <= 0;