这是一个例子,因为很难解释:
表一:
| Date | Place ID |
==========================
| 01-Feb-2013 | 1 |
| 21-Jun-2015 | 2 |
表二:
| Place ID | Date Ranked | Score |
==================================
| 1 | 01-Jan-2012 | 2 |
| 1 | 01-Jan-2014 | 1 |
| 1 | 01-Jan-2010 | 3 |
| 2 | 01-Jan-2016 | 1 |
我想要发生的是SQL(MS)是在返回第一个表的第一个记录时我希望从第二个表返回当时的分数。所以在这个例子中,得分应该是2,因为它是在2012年1月1日之后但在2014年1月1日之前。当返回表1中的第二条记录时,它应该从表2返回NULL或空白,因为在所选择的时间内没有得分。
希望有意义!!
答案 0 :(得分:2)
在SQL Server中,您可以使用outer apply
:
select t1.*, t2.score
from table1 t1 outer apply
(select top 1 t2.*
from table2 t2
where t2.placeid = t1.placeid and
t2.dateranked <= t1.dateranked
order by t2.dateranked desc
) t2;
在这种情况下,您也可以使用相关子查询执行相同的操作。