gpt4 book ai didi

SQL : Comparing multiple values in one table with a single value in another Table

转载 作者:行者123 更新时间:2023-12-04 23:44:06 24 4
gpt4 key购买 nike

我有两个表表1和表2

表 1:

-------------------------------
| Ser | StartDate | Activity |
-------------------------------
| 1 | 2002-10-13 | 1 |
| 1 | 2002-10-13 | 2 |
| 1 | 2007-09-04 | 3 |

表 2:

------------------------
|Ser|DateOfRegistration|
------------------------
| 1 | 2002-10-12 |
| 1 | 2007-09-02 |

现在,我想要的结果是,对于事件 1 和事件 2,注册日期应早于开始日期,并且日期之间的差异必须最小。同样,对于事件 3,事件 3 的注册日期应早于开始日期。结果应如下所示。

表 3:

--------------------------------------------
|Ser|StartDate |DateofRegistration|Activity|
--------------------------------------------
| 1 |2002-10-13| 2002-10-12 | 1 |
| 1 |2002-10-13| 2002-10-12 | 2 |
| 1 |2002-09-04| 2002-09-02 | 3 |

如何将表 1 和表 2 连接起来得到表 3?

最佳答案

您可以使用外部应用:

select t1.*, t2.dateofregistration
from table1 t1 outer apply
(select top (1) t2.*
from table2 t2
where t2.ser = t1.ser and t2.dateofregistration < t1.startdate
order by t2.dateofregistration desc
) t2

关于SQL : Comparing multiple values in one table with a single value in another Table,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51314563/

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