SQL Server Management Studio 2008 - 为什么我的左连接不会提供空记录?

tcs*_*ain 2 sql sql-server-2008

我试图从两个表,主表和事务表中提取记录.

我的Master表包含我的所有帐户ID.我的transaction表有这些账户的3列运行任何交易:activity date,income,和charge type.

transaction表格中,其中一些帐户可能根本不显示,因为它们在给定的日期范围内没有执行过交易.但是,当我查询它时,我仍然需要这些帐户出现在我的结果列表中.

所以我的数据看起来像这样:

     Master Table:                         Transaction Table:

    | AccountID  |              | AccountID | ChargeType | ActivityDate| Income |
    --------------              -------------------------------------------------
    |      1     |              |     2     |    2000    |  8/31/2012  | $99.00 |
    |      2     |              |     3     |    2000    |  7/31/2012  | $79.00 |
    |      3     |              |     5     |    2000    |  9/30/2012  | $79.00 |
    |      4     |
    |      5     |
Run Code Online (Sandbox Code Playgroud)

我的查询目前看起来像:

select
    a.AccountID,
    b.ChargeType,
    b.ActivityDate,
    b.Income
From
    MasterTable as A
left join
    TransactionTable as B on a.AccountID = b.AccountID
where
    a.AccountID in ('1','2','3','4','5')
    and
    b.ActivityDate between '5/1/2012' and '11/30/2012'
Run Code Online (Sandbox Code Playgroud)

根据我的理解,此查询应列出我选择的所有5个帐户,并显示NULL未在帐户中找到的帐户的值TransactionTable.

结果我期待:

        | AccountID | ChargeType | ActivityDate| Income |
        -------------------------------------------------
        |     1     |    NULL    |     NULL    |  NULL  |
        |     2     |    2000    |  8/31/2012  | $99.00 |
        |     3     |    2000    |  7/31/2012  | $79.00 |
        |     4     |    NULL    |     NULL    |  NULL  | 
        |     5     |    2000    |  9/30/2012  | $79.00 |
Run Code Online (Sandbox Code Playgroud)

我得到的结果不正确:

         | AccountID | ChargeType | ActivityDate| Income |
         -------------------------------------------------
         |     2     |    2000    |  8/31/2012  | $99.00 |
         |     3     |    2000    |  7/31/2012  | $79.00 |
         |     5     |    2000    |  9/30/2012  | $79.00 |
Run Code Online (Sandbox Code Playgroud)

我想我在这里误解了一些基本的东西.任何帮助是极大的赞赏!

提前致谢!

Gor*_*off 6

原因是您在where子句中引用了"b"表,因此过滤掉了NULL值.

将条件移动到on子句:

From
    MasterTable A left join
    TransactionTable B
    on a.AccountID=b.AccountID and
       a.AccountID in ('1','2','3','4','5') and
       b.ActivityDate between '5/1/2012' and '11/30/2012'
Run Code Online (Sandbox Code Playgroud)