2

我在按列连接两个表时遇到问题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(超过 2.000 行):

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
4

2 回答 2

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

于 2013-07-12T07:30:35.033 回答
0

If I understood your question correctly, you need to join the whole Table2 to every row of Table 1, where Table1.timestamp > Max(Table2.timestamp)? Well, the below query should do the trick, but may be you need to clarify the question.

Select * from Table1 t1, Table2 t2
Where t1.timestamp > (select MAX(t3.timestamp) from Table2 t3)
于 2013-07-11T13:26:05.777 回答