Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

sql

sql-server

I have two tables Table 1 and Table 2

Table 1:

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

Table 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. Similarly, for Activity 3, the date of registration for Activity 3 should be before the start date. The result should look like this.

Table 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?

like image 761
Roshan Joe Vincent Avatar asked Dec 06 '25 05:12

Roshan Joe Vincent


1 Answers

You can use 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
like image 162
Gordon Linoff Avatar answered Dec 08 '25 19:12

Gordon Linoff