简体   繁体   English

SQL:将一个表中的多个值与另一个表中的单个值进行比较

[英]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.

相关问题 比较一个表中2个列值的总和与第二个表SQL Server中另一个列的值 - comparing sum of 2 column values in one table with another column value in second table sql server 将一个表中一个字段的值与另一表中多个字段的总和进行比较 - Comparing the value of a field in one table to the sum of multiple fields in another table SQL将值与另一个表中的两个值进行比较以返回值 - SQL Comparing a value with two values in another table to return a value SQL-与另一个表比较后如何返回多个值,然后再次比较返回值? - SQL - How to return multiple values after comparing with another table and the return value is again compared? 将多个值从一个表连接到另一个表的共享值 - Joining multiple values from one table to a shared value on another table 将单列值标签连接到 SQL 中另一个表中的多列值 - Join a single column of value labels to multiple columns of values in another table in SQL SQL JOIN 从另一个表中的值列表中匹配 1 个表中的单个值 - SQL JOIN match single value in 1 table from a list of values in another 将单个SQL Server表中的行与其他行进行比较 - Comparing rows with another rows in a single SQL Server Table 如何通过比较一个表中的值与另一个表中的值来填充SQL中的列 - How to populate a column in SQL by comparing values from one table against another SQL 查询将多列中的值映射到另一个表中的不同值 - SQL query map values in multiple columns to different value in another table
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM