SQL query does not return records where the corresponding record is inactive

I have three Account

ABC, DEF and XYZ. ABC have two inactive Contracts

. DEF has no contract. XYZ has two contracts (one active and one inactive).

The following query returns me the output as follows.

╔════╦══════════════╦══════╗
β•‘nameβ•‘ accountId    β•‘Count β•‘
╠════╬══════════════╬══════╣
β•‘DEF β•‘ 554-050-4876 β•‘  0   β•‘
β•‘XYZ β•‘ 111-000-4345 β•‘  1   β•‘
β•šβ•β•β•β•β•©β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•©β•β•β•β•β•β•β•

      

But I expect the result to be as follows:

╔════╦══════════════╦══════╗
β•‘nameβ•‘ accountId    β•‘Count β•‘
╠════╬══════════════╬══════╣
β•‘ABC β•‘ 244-5677-444 β•‘  0   β•‘
β•‘DEF β•‘ 554-050-4876 β•‘  0   β•‘
β•‘XYZ β•‘ 111-000-4345 β•‘  1   β•‘
β•šβ•β•β•β•β•©β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•©β•β•β•β•β•β•β•

      

This means that the request should return everything Accounts

with the number of active ones Contracts

. In the absence of a Contract on the account or only inactive contracts are theirs. The query should return 0 in the Count column.

SELECT 
    a.name 
    , a.accountid 
    , COUNT(c.contractid) AS  'Count' --Number Active Of Contracts
FROM FilteredAccount AS a
LEFT OUTER JOIN FilteredContract AS c
    ON a.accountid = c.accountid
WHERE a.statecode = 0 -- Active
    AND a.customertypecode = 3 -- Active
    AND a.name IN ('ABC','XYZ')
    AND (c.statecode = 2 or c.statecode is null)
GROUP BY a.name , a.accountid;

      

Thanks in Advance.

+3


source to share


1 answer


Move all criteria JOIN

to offer ON

: at this point, you have filters in WHERE

that override yours left outer join

.

eg.



SELECT 
    a.name 
    , a.accountid 
    , COUNT(c.contractid) AS  'Count' --Number Active Of Contracts
FROM FilteredAccount AS a
LEFT OUTER JOIN FilteredContract AS c
    ON (c.statecode = 2 or c.statecode is null) and a.accountid = c.accountid
WHERE a.statecode = 0 -- Active
    AND a.customertypecode = 3 -- Active
    AND a.name IN ('ABC','XYZ')
GROUP BY a.name , a.accountid;

      

+3


source







All Articles