我有三个Account
ABC,DEF和XYZ。
ABC有两个非活动Contracts
。
DEF没有任何合同。
XYZ有两个合同(一个是活动的,一个是非活动的)。
以下查询返回输出如下。
╔════╦══════════════╦══════╗
║name║ accountId ║Count ║
╠════╬══════════════╬══════╣
║DEF ║ 554-050-4876 ║ 0 ║
║XYZ ║ 111-000-4345 ║ 1 ║
╚════╩══════════════╩══════╝
但我期待结果如下:
╔════╦══════════════╦══════╗
║name║ accountId ║Count ║
╠════╬══════════════╬══════╣
║ABC ║ 244-5677-444 ║ 0 ║
║DEF ║ 554-050-4876 ║ 0 ║
║XYZ ║ 111-000-4345 ║ 1 ║
╚════╩══════════════╩══════╝
表示,查询应返回所有Accounts
,其中包含有效Contracts
的数量。如果账户中没有合同,或者只有非活动合同。查询应在Count列中返回0。
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;
先谢谢。
答案 0 :(得分:3)
将所有JOIN
条件移至ON
条款中:此时您在WHERE
中的过滤条款覆盖了left outer join
。
e.g。
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;