Click here to Skip to main content
15,888,351 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I have two tables that I'm looking to reference between; one table holds 2000+ rows of datetimes with ID's and the second table holds just 400 -/+ datetimes.

I need to find all the datetime (dt_tbl1) in table 1 that are round about the same time as those in table 2, (table 2 is my reference point) producing a list of ID's from table 1 that are around the datetime (dt_tbl2) of table 2.

Basically finding the 400 -/+ ID's in table 1, also table 1 is 2 - 10 seconds behind table 2.

The column type IS datetime, not float, varchar or alike etc.

Hope you follow me so far.

Here's the query ;
SQL
SELECT * FROM @table2 as tbl2
inner join @table1 as tbl1 on tbl1.dt_tbl1 = tbl2.dt_tbl2


However I know the
SQL
tbl1.dt_tbl1 = tbl2.dt_tbl2
part will just look for exact matches, but I need it to find datestimes (dt_tblx) give or take 2 - 10 seconds.

Anyone know how I can elaborate the query to do this?

I'm guessing it would be something like
SQL
DATEDIFF(SS,tbl2.dt_tbl2,tbl1_dt_tbl1) <= 4


Thanks,
James
Posted
Updated 5-Jul-13 5:25am
v2

1 solution

Look at the BETWEEN command

SQL
t1.date BETWEEN DATEADD(second, 2, t2.date) AND DATEADD(second, 10, t2.date)


Or you can write multiple logic statement

SQL
t1.date > DATEADD(second, 2, t2.date) AND t1.date < DATEADD(second, 10, t2.date)


You can probably find a number of other ways too. You'll have to try them and see which is fasted.

The following article discusses these and more:

http://social.msdn.microsoft.com/Forums/sqlserver/en-US/33d56faf-7eed-455e-8d75-93d22291ae9a/allow-for-1-second-variance-in-datetime-join[^]
 
Share this answer
 
Comments
J3ffers 5-Jul-13 11:51am    
Thanks Stephen,

I've change my code as follows;

Collapse | Copy Code
inner join @table1 as tbl1 on tbl1.dt_tbl1 BETWEEN DATEADD(second, 2, tbl2.dt_tbl2) AND DATEADD(second, 10, tbl2.dt_tbl2)
or
Collapse | Copy Code
inner join @table1 as tbl1 on tbl1.dt_tbl1 > DATEADD(second, 2, tbl2.dt_tbl2) AND tbl1.dt_tbl1 < DATEADD(second, 10, tbl2.dt_tbl2)

I'm getting 19 results on either query so getting there somewhat, just got to tweak the time frame differences.

Thank you very much.

Ta,
James
[no name] 5-Jul-13 11:59am    
my 5..
Stephen Hewison 5-Jul-13 12:35pm    
Thanks

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900