将 AND & OR 与 Exists 组合

Combining AND & OR with Exists

我正在使用 MS SQL Server 2012

我已经尝试了 AND、OR 和括号的各种组合,但我无法将此查询 return 得到它应该的结果集。我可以让查询排除像 'Closed%' 这样的行,但我不能让 OR 子句也排除 'Name One'

排除基于 AccountClosedDate 条目的子查询中的第二个 AND OR 子句正在运行。

    SELECT 
    Distinct a.CompositeID,
    a.ClientID,
    a.ClientName,
    a.CompositeName,
    a.BranchName
    FROM  AllAccounts a
    WHERE (a.Compositename NOT LIKE 'Closed%' OR a.CompositeName <> 'Name One')
    AND EXISTS
    (
SELECT  DISTINCT CompositeID, CompositeName
FROM allaccounts c
WHERE c.CompositeID = a.CompositeID
AND (c.AccountClosedDate >= '1/1/2015' OR c.AccountClosedDate IS NULL))
ORDER BY a.CompositeName

示例输出我想排除名称或名称中已关闭的那些

CompositeID ClientID    ClientName  CompositeName   BranchName
8801    5318    Client1 Name Two    Firm1
7087    2311    Client2 Name Three  Firm1
4817    2311    Client3 Name Four   Firm1
11163   6863    Client4 Name Five   Firm1
4031    2540    Client5 Closed3 Firm2
5079    2061    Client6 Closed2 Firrm2
5079    1149    Client7 Closed2 Firm3
5079    2249    Client8 Closed2 Firm3
5079    1873    Client9 Closed2 Firm3
5079    960 Client10    Name One    Firm3
5079    1011    Client11    Name One    Firm3
5079    1588    Client12    Name One    Firm3
4090    1594    Client13    Name 6  Firm3

如果要根据上述 2 个条件排除名称,则需要在子句中使用 AND:

(a.Compositename NOT LIKE 'Closed%' AND a.CompositeName <> 'Name One')

当它检查每条记录时,只有当两个条件都满足时才会包括它。

我们来看几条记录:

Name             AND            OR
Name Two         True           True
Closed3          False          True
Name One         False          True

如果您在条件之间加上 OR,则您将包括所有不以 'Closed' 开头或不是 'Named One' 的记录。所有记录都满足一个或另一个条件,因此所有记录都包括在内。

所以 'Closed3' 对于使 OR 链接子句为真的第二个条件为真。同样,Name One 对第一个为真,这使得整个子句为真。