I am trying to join two tables w.r.t the nearest date. Please see the screenshot for reference.
I have Medication Table and Side Effects Table and I need to know what is the medical location for a particular side affect.
Ex 1: Medication started on 2015-07-23 (2nd row in Medication Table) and there was a Side affect on 2015-07-24 (2nd row in Side Effect Table). So this tells me that the medical location is ABDOMEN.
Ex 2: Medication started on 2018-06-19 (last row in Medication Table) and there was a Side affect on 2018-07-25 (last row in Side Effect Table). So this tells me that the medical location is THIGH.
So, here I am just trying to map the nearest dates of both the tables and get that particular Medical Location in the resulting table.
When I write the join in the below way: MID = SID AND MNAME = SNAME AND Medication Start Date <= Side Effect Date then I am getting too many records. Looks like I am missing some condition to write here. Can you please help me on this.
Thanks.
Medication Table:
MID MNAME MedicalLocation Medication Start Date
I1F-BE 132~1201 THIGH 2015-07-07
I1F-BE 132~1202 ABDOMEN 2015-07-23
I1F-BE 132~1203 ABDOMEN 2015-08-04
I1F-BE 132~1204 ABDOMEN 2015-08-18
I1F-BE 132~1205 ABDOMEN 2015-09-01
I1F-BE 132~1206 ABDOMEN 2015-09-15
I1F-BE 132~1207 ABDOMEN 2015-09-29
I1F-BE 132~1208 ABDOMEN 2015-10-13
I1F-BE 132~1209 THIGH 2015-10-27
I1F-BE 132~1210 ABDOMEN 2015-11-10
I1F-BE 132~1201 THIGH 2018-06-19
I1F-BE 132~1209 THIGH 2015-10-27
I1F-BE 132~1210 ABDOMEN 2015-11-10
I1F-BE 132~1201 THIGH 2018-06-19
Side Effect Table:
SID SNAME Side Effect Side Effect Start Date
I1F-BE 132~1201 UTI 2015-06-23
I1F-BE 132~1202 Injection Site Reaction 2015-07-24
I1F-BE 132~1203 Injection Site Reaction 2015-08-05
I1F-BE 132~1204 Viral Syndrome 2015-08-10
I1F-BE 132~1205 Injection Site Reaction 2015-08-18
I1F-BE 132~1206 Injection Site Reaction 2015-09-02
I1F-BE 132~1207 Injection Site Reaction 2015-09-16
I1F-BE 132~1208 Injection Site Reaction 2015-09-30
I1F-BE 132~1209 Injection Site Reaction 2015-10-14
I1F-BE 132~1210 Injection Site Reaction 2015-10-28
I1F-BE 132~1201 Basal Cell carcinoma 2018-07-25