如果您正在使用SQL Server,則該數據集:
DECLARE @Table1 TABLE (A VARCHAR(10), B VARCHAR(10), Time1 Datetime)
DECLARE @Table2 TABLE (A VARCHAR(10), B VARCHAR(10), Time2 Datetime)
INSERT @Table1 VALUES
('R', 'T', '11/3/14 8:30:00'),
('A', 'T', '11/3/14 8:32:00'),
('R', 'T', '11/3/14 8:40:00'),
('A', 'T', '11/3/14 8:42:00')
INSERT @Table2 VALUES
('S', 'T', '11/3/14 8:30:00'),
('U', 'T', '11/3/14 8:32:00')
您可以獲得與您可以通過交叉比較@表2表適用於:
SELECT t1.Time1 AS R_time, t.Time1 AS A_time
FROM @Table1 AS t1
CROSS APPLY
(
SELECT TOP 1 t2.Time1
FROM @Table1 AS t2
WHERE A = 'A' AND t2.Time1 >= t1.Time1
) AS t
WHERE A = 'R'
上面給出作爲輸出:
R_time A_time
-----------------------------------------------
2014-11-03 08:30:00.000 2014-11-03 08:32:00.000
2014-11-03 08:40:00.000 2014-11-03 08:42:00.000
因此,最終查詢看起來像這樣:
SELECT *
FROM @Table2 As t3
CROSS APPLY (
SELECT t1.Time1 AS R_time, t.Time1 AS A_time
FROM @Table1 AS t1
CROSS APPLY
(
SELECT TOP 1 t2.Time1
FROM @Table1 AS t2
WHERE A = 'A' AND t2.Time1 >= t1.Time1
) AS t
WHERE A = 'R'
) t4
WHERE t3.Time2 BETWEEN t4.R_time AND t4.A_time
輸出:
A B Time2 R_time A_time
-------------------------------------------------------------------------------
S T 2014-11-03 08:30:00.000 2014-11-03 08:30:00.000 2014-11-03 08:32:00.000
U T 2014-11-03 08:32:00.000 2014-11-03 08:30:00.000 2014-11-03 08:32:00.000
你能編輯你的問題並添加你想要的輸出嗎?此外,使用數據庫標記問題也很有幫助。 – 2014-11-03 20:20:01
您正在使用哪個數據庫服務器?甲骨文? SQL Server?還有其他的東西嗎?... – Shiva 2014-11-03 20:20:29
By _row pair_你的意思是按照「時間」的順序排列的2個連續的行嗎? – ForguesR 2014-11-03 20:26:56