Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Left Join does not return all results

Tags:

sql

left-join

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!

like image 744
nmoorenz Avatar asked Dec 18 '22 04:12

nmoorenz


2 Answers

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
like image 179
Carsten Massmann Avatar answered Jan 02 '23 12:01

Carsten Massmann


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
like image 27
Michał Turczyn Avatar answered Jan 02 '23 14:01

Michał Turczyn