gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 23:59:11 26 4
gpt4 key购买 nike

这是一个很难解释的例子:

表一:

| 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 中,您可以使用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;

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

关于sql - 从记录集中选择日期之间的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41266059/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com