I am creating a full outer join with a where clause. However, it can only generate inner join result. I suspect that it is due to the where clause, but I do need this where condition being added. So how can I create a query with both needs meet (both the where condition and full outer join)? Here is my query.
select
t1.key1 as key1_1
, t1.key2 as key2_1
, t1.key3 as key3_1
, t1.date as date_1
, t1.v1
, t2.key1 as key1_2
, t2.key2 as key2_2
, t2.key3 as key3_2
, t2.date as date_2
, t2.v2
from t1
full outer join t2
on t1.key1 = t2.key1 and t1.key2 = t2.key2 and t1.key3 = t2.key3
where datediff(t1.date, t2.date) between -5 and 5
;
Sample data
t1
key1 key2 key3 date v1
A1 B1 C1 2015-01-01 10
A1 B2 C2 2015-01-01 11
t2
key1 key2 key3 date v2
A1 B1 C1 2015-01-01 20
A1 B1 C1 2015-01-03 30
A1 B1 C1 2015-02-01 40
A1 B1 C1 50
A1 B1 C2 2015-01-02 60
Desired result
key1_1 key2_1 key3_1 date_1 v1 key1_2 key2_2 key3_2 date_2 v2
A1 B1 C1 2015-01-01 10 A1 B1 C1 2015-01-01 20
A1 B1 C1 2015-01-01 10 A1 B1 C1 2015-01-03 30
A1 B1 C1 2015-02-01 40
A1 B1 C1 50
A1 B1 C2 2015-01-02 60
A1 B2 C2 2015-01-01 11
These are all the scenarios that I can think of as now. I can add in if I find any missing scenarios. My point here is the fact that the following results should be included:
- if the two tables meet all those conditions set up with the keys and date, then it is included as shown in line 1 and 2 in the desired result.
- if any of those conditions is not met, then we will keep one table's information in the result as shown in line 3, 4, 5, and 6 in the desired result.
EDIT: Based on @Gordon Linoff 's suggestion, I used a union all to resolve the issue. Please see my solution in my answer post below.