tags:

views:

33

answers:

1

I have three tables similar to the following:

tblInvoices: Number | Date | Customer
tblInvDetails: Invoice | Quantity | Rate | Description
tblPayments: Invoice | Date | Amount

I have created a query called exInvDetails that adds an Amount column to tblInvDetails:

SELECT tblInvDetails.*, [tblInvDetails.Quantity]*[tblInvDetails.Rate]* AS Amount
FROM tblInvDetails;

I then created a query exInvoices to add Total and Balance columns to tblInvoices:

SELECT tblInvoices.*,
  (SELECT Sum(exInvDetails.Amount) FROM exInvDetails WHERE exInvDetails.Invoice = tblInvoices.Number) AS Total, 
  (SELECT Sum(tblPayments.Amount) FROM tblPayments WHERE tblPayments.Invoice = tblInvoices.Number) AS Payments,
  (Total-Payments) AS Balance
FROM tblInvoices;

If there are no corresponding payments in tblPayments, the fields are null instead of 0. Is there a way to force the resulting query to put a 0 in this column?

+1  A: 

Use the nz() function, as in nz(colName, 0). This will return colName, unless it is null, in which case it will return the 2nd paramter (in this case, 0).

Donnie
Thanks... That's helping. Just to clarify, I've wrapped the entire subquery using that function like so: `nz((SELECT Sum(tblPayments.Amount) FROM tblPayments WHERE tblPayments.Invoice = tblInvoices.Number), 0) AS Payments` Is that what you had intended?
jheddings
You could also just wrap the `sum` itself in `nz()`, but the end result is probably exactly the same so it's not worth worry about.
Donnie
That makes sense, and it's a little easier to read: `(SELECT nz(Sum(tblPayments.Amount), 0) FROM tblPayments WHERE tblPayments.Invoice = tblInvoices.Number) AS Payments` Thanks!
jheddings
I could be wrong, but wouldn't Sum(Nz(tblPayments.Amount, 0)) make more sense? That is, convert Null to 0 before summing? I'm not sure if it matters or if it even works (since Nz() doesn't always return the right data type, though a string "0" will likely be implicitly coerced to numeric), but that seems logically the proper way to do it (to me). Not sure it matters one bit, though.
David-W-Fenton
@David - the problem is that the `sum()` itself is returning null because no rows are matches, there aren't any `tblPayments.Amount` to run `nz()` on.
Donnie
I wasn't reading the SQL carefully -- it's a correlated subquery, and I was misreading it as an INNER join on two tables. So, yes, it has to be done on the Sum().
David-W-Fenton