Query Left Join

jsic1210

Registered User.
Local time
Today, 08:11
Joined
Feb 29, 2012
Messages
188
Hello, I'm trying to create a query to count each customer's (tblCustomer) Active or Open contracts (tblContract). I'm using a left join, but it's still not taking all entries from tblCustomer - if the count is zero, it's not showing up as a line in the query. I have 533 customers, but the query only produces 465 records. Here is my SQL statement:
Code:
SELECT tblCustomer.CustomerID, tblCustomer.CoName, Count(tblContract.ContractID) AS [Open Active Count]
FROM tblCustomer LEFT JOIN tblContract ON tblCustomer.CustomerID = tblContract.CustomerID
WHERE tblContract.Status = "Active" Or tblContract.Status = "Open"
GROUP BY tblCustomer.CustomerID, tblCustomer.CoName
Is there a way to do this without using a DCount?
 
Because of your WHERE Statement...

WHERE tblContract.Status = "Active" Or tblContract.Status = "Open"

...you need to add *Or Is Null*
 
Do you mean I need to add:

Or tblContract.Status Is Null

Because that will just add to the count by including records where the Status is Null. I want it to return 0 for customers having only contracts with statuses of "Terminated," "Inactive," Or Null.
 
Oh, then you need to add the balance because right now it is only showing the ones that have a Status of Active or Open. In other words, if you want to see all the customers then you need to provide all Status' and Is Null.
 
I'm not sure what you mean by "add the balance."

If I remove the WHERE statement, it shows all 533 records, but the count shows the count of ALL contracts. If company ABC has 1 contract that is Terminated (or Inactive or Null), and no other contracts, I want the query to return as follows:
Code:
CustomerID     Company     Open/Active Contracts
         1     ABC                  0
 
To get the 0 to show in that column, you'll need an IIf Statement, so...

Code:
SELECT tblCustomer.CustomerID, tblCustomer.CoName, tblContract.Status, IIf([Status]="Open" Or [Status]="Active",1,0) AS [Open]
FROM tblCustomer LEFT JOIN tblContract ON tblCustomer.CustomerID = tblContract.CustomerID
 

Users who are viewing this thread

Back
Top Bottom