5
votes

How can I do a one-to-many join between two datasets with proc sql in SAS to obtain the record in Dataset B is closest to a value in Dataset A?

Dataset A

#Patient     #Date of Dose
001                 2020-02-01

Dataset B

# Patient        # Lab Test         #Date of Test     # Value 
001            Test 1           2020-01-17      6
001            Test 1           2020-01-29      10

I want to do the join to select the second record in Dataset B, the record with a "Date of Test" that is the closest (less than or equal to) to the "Date of Dose" in the first dataset.

4

4 Answers

1
votes

I want to do the join to select the [..] record in Dataset B [...] with a "Date of Test" that is the closest (less than or equal to) to the "Date of Dose" in the first dataset.

You could use outer appy - if sas supports that:

select a.*, b.*
from a
outer apply(
    select top 1 b.*
    from b 
    where b.patient = a.patient and b.date_of_test <= a.date_of_dose
    order by b.date_of_test desc
) b

Another solution is to join with a not exists condition:

select a.*, b.*
from a
left join b 
    on  b.patient = a.patient
    and b.date_of_test <= a.date_of_dose
    and not exists (
        select 1
        from b b1
        where 
            b1.patient = a.patient
            and b1.date_of_test <= a.date_of_dose
            and b1.date_of_test > b.date_of_test 
    )
1
votes

Calculate the absolute difference between both dates and select the minimum date with a having clause. You'll need to do additional logic, such as distinct, to remove any duplicates.

proc sql noprint;
    select t1.patient
         , t1.date_of_dose
         , abs(t1.date - t2.date) as date_dif
    from dataset_A as t1
    LEFT JOIN
         dataset_B as t2
    ON t1.patient = t2.patient
    where t1.date <= t2.date
    group by t1.patient
    having calculated date_dif = min(calculated date_dif)
    ;
quit;
1
votes

try this:

SELECT TOP 1 *
FROM (
    SELECT DSA.Patient
        ,DSA.Date_Of_Dose
        ,DSB.Date_Of_Test
        ,DATEDIFF(Day, DSA.Date_Of_Dose, DSA.Date_Of_Dose) Diff
    FROM DataSetA DSA
    JOIN DataSetB DSB ON DSA.Patient = DSB.Patient
    ) Data
WHERE ABS(Diff) = MIN(ABS(Diff));

Sorry, I got no way to know if this is working 'cause I'm not at home. I hope it helps you.

1
votes

I want to do the join to select the second record in Dataset B, the record with a "Date of Test" that is the closest (less than or equal to) to the "Date of Dose" in the first dataset.

I would recommend cross-joining Date of Test and Date of Dose, and calculate absolute difference between the dates using intck() function, and leave the minimal value.