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.
source to share
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;
source to share