It looks like a correlated subquery is one way to do what you want. In standard SQL, this look like:
select a.*,
(select b.income
from b
where b.date <= a.date
order by b.date desc
fetch first 1 row only
) as income
from a;
Note: Not all databases support the fetch first
clause. All support similar functionality, using limit
, select top
or something similar.
You can take a different approach if you like as well. If the second table had ranges where the income were know rather than a single date, then you could use a join:
select a.*, b.income
from a left join
(select b.*, lead(date) over (order by date) as next_date
from b
) b
on b.date <= a.date and
(b.next_date is null or b.next_date > a.date);
This approach has the advantage that it is easier to fetch multiple columns from b
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…