proc sql join 在最接近日期的 SAS 中

Gle*_*enn 5 sql join date sas proc

如何在 SAS 中使用 proc sql 在两个数据集之间进行一对多连接以获得数据集 B 中最接近数据集 A 中的值的记录?

数据集 A

#Patient     #Date of Dose
001                 2020-02-01
Run Code Online (Sandbox Code Playgroud)

数据集 B

# Patient        # Lab Test         #Date of Test     # Value 
001            Test 1           2020-01-17      6
001            Test 1           2020-01-29      10
Run Code Online (Sandbox Code Playgroud)

我想进行连接以选择数据集 B 中的第二条记录,该记录的“测试日期”与第一个数据集中的“给药日期”最接近(小于或等于)。

GMB*_*GMB 2

我想要进行连接以选择数据集 B [...] 中的 [..] 记录,其“测试日期”与第一个中的“剂量日期”最接近(小于或等于)数据集。

你可以使用outer apply- 如果 sas 支持它:

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
Run Code Online (Sandbox Code Playgroud)

另一种解决方案是加入条件not exists

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 
    )
Run Code Online (Sandbox Code Playgroud)