Hello,
I'm afraid I'm gonna need some gosu help with a query I'm making
I have sales representatives who visit clients, after which they (usually) send them one or more mails.
There are two tables with their fields below:
- VisitTable
ID
Rep_Name
CustomerKey
VisitDate
- MailTable
Rep_Name
CustomerKey
MailDate
For 1 visit, there are 0 to n mails.
What I want, is a query that tells me when my sales rep visited my customer (so my entire visit table), with in the next column the MailDate (if he never sent a mail, leave it blank). If there are more mails for 1 visit, just duplicate the visit rows.
A mail belongs to the visit that is the closest in the past.
Let's say i have 2 records in my sales rep visit table
ID | Rep | Customer | VisitDate
1 | John | Brian | 01/01/2015
2 | John | Brian | 02/03/2015
And 3 records in my mail table
ID | Rep | Customer | MailDate
1 | John | Brian | 02/01/2015
2 | Johan | Brian | 25/01/2015
3 | Johan | Brian | 08/03/2015
Then I'd like my query to say
ID | Rep | Customer | VisitDate | MailDate
1 | John | Brian | 01/01/2015 | 02/01/2015
1 | John | Brian | 01/01/2015 | 25/01/2015
2 | John | Brian | 02/03/2015 | 08/03/2015
The following query doesn't seem to work, because I don't get ALL my visits (I want to see my visits even if there are no mails)
Also, I don't know how I can say that an email doesn't only have to be greater than the visit date, but also small than the visit date of the next visit...
SELECT
Visit.ID
, Visit.Rep_Name
, Visit.CustomerKey
, Visit.VisitDate
, Mail.MailDate
FROM
Mail RIGHT JOIN Visit ON (Mail.CustomerKey = Visit.CustomerKey) AND (Mail.Rep_Name = Visit.Rep_Name)
WHERE
(Mail.MailDate)>=[visit].[VisitDate];
Does anyone have an idea?
Regards,
Mikey