【问题标题】:SQL query not returning records where related record is inactiveSQL查询不返回相关记录处于非活动状态的记录
【发布时间】:2014-10-08 06:12:28
【问题描述】:

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

提前致谢。

【问题讨论】:

  • 您在 c 上有一个左外连接,然后将其包含在 where 子句中。这使它成为一个内部连接。尝试将AND (c.statecode ... 移动到ON
  • +1 使用过滤视图

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


【解决方案1】:

将所有JOIN 条件移动到ON 子句中:目前您在WHERE 中有过滤条件,它会覆盖您的left outer join

例如

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;

【讨论】:

    猜你喜欢
    • 2011-08-19
    • 1970-01-01
    • 2019-12-21
    • 1970-01-01
    • 2013-10-31
    • 2017-02-05
    • 2019-11-18
    • 2011-07-18
    • 1970-01-01
    相关资源
    最近更新 更多