>I have two tables - we'll call them Customer and Bill. A customer can have zero or many bills, and it is linked by the CustomerID. What I want to do is pull a customer by CustomerID and also pull their last bill only if it is within 30 days old. If there isn't a bill that fits that criteria, I want null value.
>
>Can I do this with a JOIN? Anybody have any advice on how to do the filtering in the JOIN statement?
Something like that
DECLARE @WantedDate datetime
SET @WantedDate = '20070412'
SELECT Customer.*,
Tbl2.*
FROM Customer
LEFT JOIN (SELECT CustomerId, (other fields from BILL)
FROM Bill
INNER JOIN (SELECT CustomerId, MAX(BillDate) AS BillDate
FROM Bill
WHERE BillDate BETWEEN DateAdd(dd,-30, @WantedDate) AND @WantedDate
GROUP BY CustomerId) Tbl1
ON Bill.CustomerId = Tbl1.CustomerId AND
Bill.BillDate = Tbl1.BillDate) Tbl2
ON Customer.CustomerId = Tbl2.CustomerId
not tested
Against Stupidity the Gods themselves Contend in Vain - Johann Christoph Friedrich von Schiller
The only thing normal about database guys is their tables.