Test_PI
CustomerID Product_Interest_Date Product_Interest ---------- --------------------- ---------------- 1 2014-09-07 Interest1 1 2014-09-08 Interest2 1 2014-09-15 Interest3 1 2014-09-28 Interest4
Test_Leads
CustomerID Lead_Date Lead_Source ---------- ---------- ----------- 1 2014-09-07 Source1 1 2014-09-14 Source2 2 2014-09-15 Source3 1 2014-09-21 Source4
The trick here is to use an unequal join as part of a subquery to identify the most recent Lead_Date for each Product_Interest_Date. Inquiry
SELECT pi.CustomerID, pi.Product_Interest_Date, l.Lead_Date FROM Test_PI pi INNER JOIN Test_Leads l ON pi.CustomerID = l.CustomerID AND pi.Product_Interest_Date >= l.Lead_Date
returns
CustomerID Product_Interest_Date Lead_Date ---------- --------------------- ---------- 1 2014-09-07 2014-09-07 1 2014-09-08 2014-09-07 1 2014-09-15 2014-09-07 1 2014-09-15 2014-09-14 1 2014-09-28 2014-09-07 1 2014-09-28 2014-09-14 1 2014-09-28 2014-09-21
Notice how two matches are returned for 09-15, and three matches are returned for 09-28. We are only interested in the latter, so we will select this request a little
SELECT pi.CustomerID, pi.Product_Interest_Date, Max(l.Lead_Date) AS MaxOfLead_Date FROM Test_PI pi INNER JOIN Test_Leads l ON pi.CustomerID = l.CustomerID AND pi.Product_Interest_Date >= l.Lead_Date GROUP BY pi.CustomerID, pi.Product_Interest_Date
which returns
CustomerID Product_Interest_Date MaxOfLead_Date ---------- --------------------- -------------- 1 2014-09-07 2014-09-07 1 2014-09-08 2014-09-07 1 2014-09-15 2014-09-14 1 2014-09-28 2014-09-21
Now we can join the two tables along with this query to put it all together
SELECT Test_PI.CustomerID, Test_PI.Product_Interest_Date, Test_PI.Product_Interest, Test_Leads.Lead_Date, Test_Leads.Lead_Source FROM ( Test_PI INNER JOIN ( SELECT pi.CustomerID, pi.Product_Interest_Date, Max(l.Lead_Date) AS MaxOfLead_Date FROM Test_PI pi INNER JOIN Test_Leads l ON pi.CustomerID = l.CustomerID AND pi.Product_Interest_Date >= l.Lead_Date GROUP BY pi.CustomerID, pi.Product_Interest_Date ) latest ON Test_PI.CustomerID = latest.CustomerID AND Test_PI.Product_Interest_Date = latest.Product_Interest_Date ) INNER JOIN Test_Leads ON Test_Leads.CustomerID = latest.CustomerID AND Test_Leads.Lead_Date = latest.MaxOfLead_Date
return
CustomerID Product_Interest_Date Product_Interest Lead_Date Lead_Source ---------- --------------------- ---------------- ---------- ----------- 1 2014-09-07 Interest1 2014-09-07 Source1 1 2014-09-08 Interest2 2014-09-07 Source1 1 2014-09-15 Interest3 2014-09-14 Source2 1 2014-09-28 Interest4 2014-09-21 Source4