Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/76.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 从日期之间的记录集中选择字段_Sql_Sql Server - Fatal编程技术网

Sql 从日期之间的记录集中选择字段

Sql 从日期之间的记录集中选择字段,sql,sql-server,Sql,Sql Server,下面是一个很难解释的例子: 表一: | Date | Place ID | ========================== | 01-Feb-2013 | 1 | | 21-Jun-2015 | 2 | 表二: | Place ID | Date Ranked | Score | ================================== | 1 | 01-Jan-2012 | 2 | | 1 | 0

下面是一个很难解释的例子:

表一:

| 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实现的是,当返回表1的第一条记录时,我想从第二个表返回当时的分数。因此,在本例中,分数应为2,因为2012年1月1日之后至2014年1月1日之前。当返回表1中的第二条记录时,它应该从表2中返回NULL或空白,因为在所选时间内不存在任何分数


希望这是有意义的

在SQL Server中,您可以使用外部应用:

在这种情况下,您也可以对相关子查询执行相同的操作

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;