I am using SQL Server (I believe it is 2005).
I have TableA
that has 2 columns and 439 rows (each row is unique).
+----------+
|ID | Name |
+----------+
I have TableB
that has 35 columns and many hundreds of thousand rows (each row is also unique).
+------------------------------------------------------------------------------+
|Date | ID | Name | Blah1 | Blah2 | ... | Hour1 | Hour2 | Hour3 | ... | Hour24 |
+------------------------------------------------------------------------------+
Each row in TableB
has hourly observations and some other house keeping information. Now for testing purposes I am only interested in today's date i.e 4/19/2013.
If I do:
Select count(*)
from TableB
where Date = '4/19/2013 12:00:00 AM'
I get 10526, which is correct as there are 10526 distinct locations for which there is hourly observation data each day.
I want to LEFT JOIN TableA and TableB on a.id = b.id
, which SHOULD produce a result that has 439 rows.
Unfortunately, the result has 246 rows. How can this be? Isn't a LEFT JOIN
suppose to return all rows in TableA
regardless of whether there was a match in TableB
?
*EDIT*
The complete query I used was:
select *
from TableA as a
left join TableB as b on a.id = b.id
where RealDate = '4/20/2013 12:00:00 AM'
Left joins can increase the number of rows in the left table if there are multiple matches in the right table.
There are two line items for ID 1003 in the second table, so the result of the join will be 2 line items. So, if your secondary tables have more than one row for the key you're joining with, then the result of the join will be multiple rows, resulting in more rows than the left table.
condition. If I use the table in a left join with the same where condition my row count increases.
The SQL LEFT JOIN returns all rows from the left table, even if there are no matches in the right table. This means that if the ON clause matches 0 (zero) records in the right table; the join will still return a row in the result, but with NULL in each column from the right table.
Try this:
select * from TableA as a
left join (SELECT * from TableB where RealDate = '4/20/2013 12:00:00 AM') as b
on a.id = b.id
Or this:
select * from TableA as a
left join TableB as b on (a.id = b.id AND RealDate = '4/20/2013 12:00:00 AM')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With