通过t1.datetime和MAX(t2.datetime)连接表

时间:2013-07-11 12:48:07

标签: sql join sql-server-2008-r2 max

我在使用datetime列加入两个表时遇到问题。

我需要加入Table1.datetime>MAX(Table2.datetime)之类的东西。 我没有任何其他专栏可以加入。你能救我吗?

Table1(超过370.000行)的示例:

timestamp                data1  data2  data3
-----------------------  -----  -----  -----
2011-05-09 08:55:19.990  x1     w12    j3
2011-05-09 08:56:19.990  x4     w22    j3
2011-05-09 08:57:19.990  x5     w23    j3
2011-05-09 08:58:19.990  x7     w25    j3
2011-05-09 08:59:19.990  x2     w19    j3
2011-05-09 09:01:19.990  x3     w18    j3

Table2(超过2000行)的示例:

timestamp                data8
-----------------------  -----
2011-05-09 07:55:11.990  y1
2011-05-09 07:56:13.990  y9
2011-05-09 08:17:14.990  y3
2011-05-09 08:28:15.990  y8
2011-05-09 08:59:16.990  y5
2011-05-09 09:02:19.990  y6

因此Table1加入Table2的数据应具有值:

timestamp                data1  data2  data3  timestamp                data8
-----------------------  -----  -----  -----  -----------------------  -----
2011-05-09 08:55:19.990  x1     w12    j3     2011-05-09 08:28:15.990  y8
2011-05-09 08:56:19.990  x4     w22    j3     2011-05-09 08:28:15.990  y8
2011-05-09 08:57:19.990  x5     w23    j3     2011-05-09 08:28:15.990  y8
2011-05-09 08:58:19.990  x7     w25    j3     2011-05-09 08:28:15.990  y8
2011-05-09 08:59:19.990  x2     w19    j3     2011-05-09 08:59:16.990  y5
2011-05-09 09:01:19.990  x3     w18    j3     2011-05-09 08:59:16.990  y5

2 个答案:

答案 0 :(得分:1)

使用CROSS APPLY和TOP运算符

的选项
SELECT *
FROM dbo.Table1 t1 CROSS APPLY (
                                SELECT TOP 1 t2.[TIMESTAMP], t2.data8
                                FROM dbo.Table2 t2
                                WHERE t2.[TIMESTAMP] < t1.[TIMESTAMP]
                                ORDER BY t2.[TIMESTAMP] DESC
                                ) o

请参阅SQLFiddle

上的演示

答案 1 :(得分:0)

如果我正确理解了您的问题,您需要将整个Table2加入表1的每一行,其中Table1.timestamp&gt;马克斯(Table2.timestamp)?好吧,下面的查询应该可以解决问题,但可能需要澄清这个问题。

Select * from Table1 t1, Table2 t2
Where t1.timestamp > (select MAX(t3.timestamp) from Table2 t3)