Table 1:
PHONE_NUMBER | DATE
--------------------------
10005 | 5/10/2013
15555 | 7/17/2013
58746 | 9/20/2013
Table 2:
PHONE_NUMBER | DATE
--------------------------
10005 | 5/12/2013
10005 | 5/16/2013
15555 | 6/17/2013
15555 | 7/19/2013
58746 | 8/22/2013
58746 | 12/26/2013
58746 | 9/20/2013
From the above two tables, I want to extract data from Table 2 by mapping Table 1 phonenumber against table 2 phonenumber and the date in the Table 2 can exactly the same date or +/-5 days of the respective phonenumber's date of the table 1's.
Table 2 will have duplicated phonenumbers and all the duplicates matching the above condition should extract.
If I understand your question this should meet the requirement:
SELECT
t2.phone_number
, convert(varchar(10),t2.[date],121) as t2_date
, convert(varchar(10),t1.[date],121) as t1_date
, datediff(DAY,t1.[date], t2.[date]) as diff_dates
FROM table2 AS t2
INNER JOIN table1 AS t1 ON t2.phone_number = t1.phone_number
AND t2.[date] between dateadd(day,-5,t1.[date]) and dateadd(day,5,t1.[date])
see: this sqlfiddle
results from the sample data:
| PHONE_NUMBER | T2_DATE | T1_DATE | DIFF_DATES |
|--------------|------------|------------|------------|
| 10005 | 2013-05-12 | 2013-05-10 | 2 |
| 15555 | 2013-07-19 | 2013-07-17 | 2 |
| 58746 | 2013-09-20 | 2013-09-20 | 0 |