基于时间戳加入两个表,彼此间隔5分钟

时间:2018-04-25 22:09:30

标签: sql sql-server join timestamp

我想基于时间戳加入两个表,问题是我注意到两个表没有完全相同的时间戳,所以我想使用最近的时间戳以5分钟的间隔加入它们。

 Freezer |       Timestamp      | Temperature_1
     1      2018-04-25 09:45:00       10  
     1      2018-04-25 09:50:00       11   
     1      2018-04-25 09:55:00       11


Freezer |       Timestamp      | Temperature_2
     1      2018-04-25 09:46:00       15  
     1      2018-04-25 09:52:00       13   
     1      2018-04-25 09:59:00       12   

我想要的结果是:

Freezer |       Timestamp      | Temperature_1 | Temperature_2
     1      2018-04-25 09:45:00       10             15
     1      2018-04-25 09:50:00       11             13
     1      2018-04-25 09:55:00       11             12

我正在处理的当前查询是:

SELECT A.Freezer, A.Timestamp, Temperature_1,Temperature_2 From TABLE_A as A
RIGHT JOIN TABLE_B as B
ON A.FREEZER = B.FREEZER
WHERE A.Timestamp = B.Timestamp (this of course doesn't work because timestamps aren't the same)

2 个答案:

答案 0 :(得分:1)

这样做你想要的吗?

SELECT . . .
From TABLE_A A JOIN
     TABLE_B B
     ON A.FREEZER = B.FREEZER AND
        A.Timestamp >= DATEADD(minute, -5, B.TimeStamp) AND
        A.Timestamp <= DATEADD(minute, 5, B.TimeStamp) ;

我认为没有理由选择外JOIN

如果要查找最近的时间戳,请使用apply

select . . .
from table_a a cross apply
     (select top (1) b.*
      from table_b b
      where a.freezer = b.freezer 
      order by abs(datediff(second, a.timestamp, b.timestamp))
     ) b;

您可以在子查询中添加where子句,以将匹配范围限制为五分钟。

答案 1 :(得分:1)

尝试此查询

SELECT T1.freezer, 
       T1.[timestamp], 
       T1.temperature_1, 
       T2.temperature_2 
FROM   table_1 T1
       INNER JOIN table_2 T2
       ON T1.[timestamp] = Dateadd(minute, -(Cast(Datepart(minute, T2.[timestamp]) AS INT) % 5), T2.[timestamp]) 

结果

+---------+-------------------------+---------------+---------------+
| Freezer |        Timestamp        | Temperature_1 | Temperature_2 |
+---------+-------------------------+---------------+---------------+
|       1 | 2018-04-25 09:45:00.000 |            10 |            15 |
|       1 | 2018-04-25 09:50:00.000 |            11 |            13 |
|       1 | 2018-04-25 09:55:00.000 |            11 |            12 |
+---------+-------------------------+---------------+---------------+

演示:http://www.sqlfiddle.com/#!18/ffa1e/2/0