[英]SQL : Comparing multiple values in one table with a single value in another Table
I have two tables Table 1 and Table 2 我有两张表1和表2
Table 1: 表格1:
-------------------------------
| Ser | StartDate | Activity |
-------------------------------
| 1 | 2002-10-13 | 1 |
| 1 | 2002-10-13 | 2 |
| 1 | 2007-09-04 | 3 |
Table 2: 表2:
------------------------
|Ser|DateOfRegistration|
------------------------
| 1 | 2002-10-12 |
| 1 | 2007-09-02 |
Now, the result that I want is such that for Activity 1 and 2 the Date of registration should be before the Start Date and difference between the dates must be the least. 现在,我想要的结果是,对于活动1和2,注册日期应该在开始日期之前,并且日期之间的差异必须最小。 Similarly, for Activity 3, the date of registration for Activity 3 should be before the start date. 同样,对于活动3,活动3的注册日期应该在开始日期之前。 The result should look like this. 结果应该是这样的。
Table 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 |
How can I join Table 1 and 2 to get Table 3? 如何将表1和表2连接到表3?
You can use outer apply
: 你可以使用outer apply
:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.