SQL查询不返回相关记录处于非活动状态的记录

时间:2014-08-14 14:30:09

标签: sql-server sql-server-2008 dynamics-crm-2011 dynamics-crm

我有三个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;

先谢谢。

1 个答案:

答案 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;