sql—查找表b中相对于表a日期的最新值

hjzp0vay  于 2021-08-13  发布在  Java
关注(0)|答案(1)|浏览(369)

我现在有两张table: table a 以及 table b .

我的目标是从 table b 并使用联接将其添加为新列 table a (然而,当我说“最新的”时,我真正的意思是“最新的” Event_Date 列在 table a )
我想这将是一个 left join 但我拉不动 Score . 我只知道怎么拉日期:

select 
a.Entity_ID,
a.Event_Date,
max(b.date_processed) --I want to change this to the score correlated to the max date_processed
from myTable a
left join myTable b
on a.Entity_ID = b.Entity_ID and b.date_processed < a.event_date
Group By a.Entity_ID, a.Event_Date, b.Date_Processed

任何帮助都将不胜感激

emeijp43

emeijp431#

我知道你想要的是 tabebevent_datetablea .
一个选项使用具有行限制子句的相关子查询:

select 
    a.*,
    (
        select b.score
        from tableb b
        where b.entity_id = a.entity_id and b.date_processed <= a.event_date
        order by b.date_processed desc
        fetch first 1 row only
    ) most_recent_score
from tablea a

相关问题