nmoorenz
nmoorenz

Reputation: 77

SQL Left Join does not return all results

I have two tables that I'm trying to join for customers that are going through a process. All customers get to step one, but only some progress to step two (table 2). Customers may start this process more than once at different times, and may get to step two in none, one, or many months. I'd like to know how many make this progression. Tables as an example:

Table_1

Cust1    1-Jan    
Cust2    10-Jan
Cust3    15-Jan
Cust1    2-Feb

Table_2

Cust1    5-Jan
Cust2    16-jan

My query to return results is:

SELECT t1.Cust, t1.Date1, t2.Date2
FROM Table_1 t1
LEFT JOIN Table_2 t2 ON t1.Cust = t2.Cust
WHERE t2.Date is missing OR (t2.Date - t1.Date > 0 AND t2.Date - t1.Date < 10);

This returns:

Cust1  1-Jan    5-Jan
Cust2  10-Jan   16-Jan
Cust3  15-Jan

When what I want the query to return is:

Cust1  1-Jan    5-Jan
Cust1  2-Feb
Cust2  10-Jan   16-Jan
Cust3  15-Jan

The query seems to join Cust1 with 2-Feb and 5-Jan and then eliminates this because it doesn't match the filter. But I need the filter because Cust1 comes back in March. How do I keep this Feb entry in the final output? Help!

Upvotes: 4

Views: 324

Answers (3)

Jaydip Jadhav
Jaydip Jadhav

Reputation: 12309

The query seems to join Cust1 with 2-Feb and 5-Jan and then eliminates this because it doesn't match the filter.

Right!! This is because, whenever you use LEFT JOINed Table in WHERE clause then this will change the behaviour of LEFT JOIN and Act as INNER JOIN and As you know the INNER JOIN return only matching records.

To get work around to this problem Use WHERE Clause conditions IN Joining logic

Upvotes: 3

Michał Turczyn
Michał Turczyn

Reputation: 37367

I suppose, that customers can start a process once a month (at least that what I observed), so it could be joined lie this:

SELECT t1.Cust, t1.Date1, t2.Date2
FROM Table_1 t1
LEFT JOIN Table_2 t2 ON (t1.Cust = t2.Cust AND DATEDIFF(MONTH, t1.Date1, t2.Date2) = 0)

Generally, you can use DATEDIFF to specify more narrow period, i.e. if you would like this difference to be less than 10 days you could use:

DATEDIFF(DAY, t1.Date1, t2.Date2) <= 10

Upvotes: 3

Carsten Massmann
Carsten Massmann

Reputation: 28196

Put the where condition into your on clause:

SELECT t1.Cust, t1.Date1, t2.Date2
FROM Table_1 t1
LEFT JOIN Table_2 t2 ON t1.Cust = t2.Cust 
                    AND t2.Date - t1.Date > 0 
                    AND t2.Date - t1.Date < 10

Upvotes: 5

Related Questions