I am trying to pull records from two tables, a master table, and a transaction table.
My Master table contains all of my account IDs. My transaction table has any transaction run by these accounts with 3 columns: activity date, income, and charge type.
In the transaction table, some of these accounts may not appear at all because they have not performed a transaction during a given date range. However, I still need these accounts to appear on my result list when I query them.
So my data would look like this:
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 |
My query currently looks like:
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'
From what I understand, this query should list all 5 accounts I’ve chosen, and display NULL values for the accounts not found in the TransactionTable.
Results I expect:
| 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 |
The incorrect results I receive instead:
| 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 |
I assume I am misunderstanding something fundamental here. Any help is greatly appreciated!
Thanks in advance!
The reason is that you have the “b” table referenced in the
whereclause, so NULL values are filtered out.Move the condition to the
onclause: