Я быстро попробовал это, и вот решение, которое работает в несколько этапов.Это, вероятно, не подходит для цели, но, по крайней мере, это начало.
IF OBJECT_ID('tempdb..#shovel') IS NOT NULL
DROP TABLE #shovel;
IF OBJECT_ID('tempdb..#truck') IS NOT NULL
DROP TABLE #truck;
IF OBJECT_ID('tempdb..#matches1') IS NOT NULL
DROP TABLE #matches1;
IF OBJECT_ID('tempdb..#matches2') IS NOT NULL
DROP TABLE #matches2;
SELECT 'EX7016' AS Equipment, '1000' AS Code, '0' AS Start_Time
INTO #shovel
UNION ALL
SELECT 'EX7016' AS Equipment, '4030' AS Code, '1200' AS Start_Time
UNION ALL
SELECT 'EX7016' AS Equipment, '1000' AS Code, '1400' AS Start_Time
SELECT 'DT5188' AS Equipment, 'EX7016' AS Shovel, '1002' AS Code, '0' AS Start_Time
INTO #truck
UNION ALL
SELECT 'DT5188' AS Equipment, 'EX7016' AS Shovel, '1003' AS Code, '1000' AS Start_Time
UNION ALL
SELECT 'DT5188' AS Equipment, 'EX7016' AS Shovel, '1004' AS Code, '1500' AS Start_Time
UNION ALL
SELECT 'DT5188' AS Equipment, 'EX7016' AS Shovel, '1005' AS Code, '2000' AS Start_Time;
--Make a list of cases where the #shovel table has code > 2000, and the time starts when the truck is in a 1003 code
SELECT
s.Equipment,
s.Start_Time,
t.Shovel
INTO
#matches1
FROM
#shovel s
INNER JOIN #truck t ON t.Shovel = s.Equipment
WHERE
s.Code > '2000'
AND t.Code = '1003';
--Find cases where the shovel goes back to a 1000 code
SELECT
m.Equipment,
s.Start_Time,
m.Shovel
INTO
#matches2
FROM
#matches1 m
INNER JOIN #shovel s ON s.Equipment = m.Equipment AND s.Start_Time > m.Start_Time AND s.Code = '1000';
--Finally, insert matching rows back into the #truck table (do we only do this if there is a match in both tables?)
INSERT INTO #truck SELECT Equipment, Shovel, '1002' AS Code, Start_Time FROM #matches1;
INSERT INTO #truck SELECT Equipment, Shovel, '1003' AS Code, Start_Time FROM #matches2;
SELECT * FROM #truck ORDER BY Start_Time;