Search code examples
sqlsql-serverjoin

Joining by datetimefield SQL Server


I have two tables that holds inforamtion for SKU.

Log table has datetimefield 2008-10-26 06:21:59.820
the other table has datetimefield 2008-10-26 06:22:02.313

I want to include this datetime fields in join for these 2 tables.

Is it possible to join to tables with datetime fields that has difference not more than 3 seconds? What is the best way to do that?


Solution

  • This is one way to do it:

    select * from table_a, table_b
    where table_a.sku = table_b.sku
    and abs(datediff(second,table_a.datetime,table_b.datetime))<=3
    

    Be careful, with big tables this kind of join can be very slow.