簡體   English   中英

SQL:將一個表中的多個值與另一個表中的單個值進行比較

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

我有兩張表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?

你可以使用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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM