我有:
Table A
-------
N0 Date Time
-----------------------------
123 20-Apr-11 10:00:05
123 20-Apr-11 10:00:06
456 20-Apr-11 10:00:01
456 20-Apr-11 10:00:02
Table B
-------
N0 Date Time
-----------------------------
123 20-Apr-11 10:00:02
123 20-Apr-11 10:00:04
123 20-Apr-11 10:00:05
123 20-Apr-11 10:00:07
123 20-Apr-11 10:00:08
456 20-Apr-11 10:00:04
456 20-Apr-11 10:00:05
456 20-Apr-11 10:00:02
456 20-Apr-11 10:00:03
456 20-Apr-11 10:00:00
A.N0 A.Date A.Time B.Time
----------------------------------------
123 20-Apr-11 10:00:05 10:00:07
123 20-Apr-11 10:00:06 10:00:08
456 20-Apr-11 10:00:01 10:00:03
456 20-Apr-11 10:00:02 10:00:04
如果您看到上述结果,则B.time
应大于A.time
且不应重复加入。
请建议我如何使用oracle SQL语句执行此操作。
答案 0 :(得分:0)
以下内容可以为您提供所需的输出:
With NumberedA As
(
Select *
, Row_Number() Over ( Partition By N0, Date Order By Time ) Num
From TableA
)
, NumberedB As
(
Select A.N0, A.Date
, A.Time ATime
, B.Time BTime
, Row_Number() Over ( Partition By A.N0, A.Date, A.Time Order By B.Time ) Num
From TableA A
Join TableB B
On B.N0 = A.N0
And B.Date = A.Date
And B.Time > A.Time
)
Select A.N0, A.Date, A.Time, B.Time
From NumberedA A
Join NumberedB B
On B.N0 = A.N0
And B.Date = A.Date
And B.ATime = A.Time
And B.Num = A.Num
那就是说,如果我们理解你的请求背后的推理,那将会有所帮助。
答案 1 :(得分:0)
看看这个
但需要在表B中创建一个名为“Flag”的新列
CREATE OR REPLACE PROCEDURE Proc_test
IS
BEGIN
FOR i IN (SELECT *
FROM a
ORDER BY NAME, date, time)
LOOP
FOR j IN (SELECT *
FROM b
ORDER BY NAME, date, time)
LOOP
IF i.NAME = j.NAME
AND i.date = j.date
AND j.flag IS NULL
AND i.time < j.time
THEN
INSERT INTO target
(NAME, date, time1, time2
)
VALUES (i.NAME, i.date, i.time, j.time
);
UPDATE b
SET flag = 'Y'
WHERE NAME = i.NAME AND date = i.date AND time = j.time;
COMMIT;
END IF;
END LOOP;
END LOOP;
END;
/
工作正常......