SQL Left Join does not return all results

ⅰ亾dé卋堺 提交于 2020-05-15 03:44:29

问题


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!


回答1:


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



回答2:


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



回答3:


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



来源:https://stackoverflow.com/questions/46067701/sql-left-join-does-not-return-all-results

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!