Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
Author |
Topic |
bmturney
Starting Member
7 Posts |
Posted - 2012-03-08 : 17:42:35
|
I have an issue that I think should be possible, but I haven't been able to figure out an efficient way to do it via SQL.I have two tables... each table contains data keyed by a datetime field, but the datetime keys aren't exact matches for the correlating records in each file. I want to join the records in table1 with the records in table2 so that for each record in table1 it gets matched up with the most recent correlating record from table2 where the collection time for the record in table2 does not exceed the collection time for the record in table1 (confusing, right?)Here's an example:Table 1Time1 ObjID1 Data1 Data2 ObjID213:40:45 1 aaa bbb 10113:42:32 2 ccc ddd 10213:43:18 1 eee fff 10113:45:56 1 ggg hhh 10113:48:43 2 iii jjj 102Table 2Time2 ObjID2 Data3 Data413:39:19 101 zzz yyy13:42:28 102 xxx www13:45:31 101 vvv uuu13:46:34 101 ttt sss13:48:56 102 rrr qqq13:50:43 101 ppp oooSo the resulting records will look like thisTime1 ObjID1 Data1 Data2 ObjID2 Time2 Data3 Data413:40:45 1 aaa bbb 101 13:39:19 zzz yyy13:42:32 2 ccc ddd 102 13:42:28 xxx www13:43:18 1 eee fff 101 13:39:19 zzz yyy13:45:56 1 ggg hhh 101 13:45:31 vvv uuu13:48:43 2 iii jjj 102 13:42:28 xxx www |
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2012-03-08 : 17:57:23
|
[code]SELECT t1.Time1, t1.ObjID1,t1.Data1,t1.Data2,t1.ObjID2,t2.Time2,t2.Data3,t2.Data4FROM table1 t1CROSS APPLY (SELECT TOP 1 Time2,Data3,Data4 FROM table2 WHERE ObjID2 = t1.ObjID2 AND Time2 < Time1 ORDER BY Time2 DESC) t2[/code]------------------------------------------------------------------------------------------------------SQL Server MVPhttp://visakhm.blogspot.com/ |
 |
|
bmturney
Starting Member
7 Posts |
Posted - 2012-03-09 : 08:31:24
|
Thanks!!!! |
 |
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2012-03-09 : 11:49:00
|
welcome------------------------------------------------------------------------------------------------------SQL Server MVPhttp://visakhm.blogspot.com/ |
 |
|
|
|
|
|
|