我會建議使用下面的代碼。這個想法是選擇所有具有非空條目值的行(en),然後將其與具有相同ID但具有大於條目時間戳(,例如)的退出時間戳的記錄結合。最後,左連接(xex)用於確保沒有其他具有在en和ex之間的退出時間戳的行。
-- data stored as per original question
CREATE TABLE #tbl
(
[id] INT NOT NULL,
[entrance] DATETIME,
[exit] DATETIME
);
INSERT INTO #tbl ([id], [entrance], [exit])
VALUES (10000, '2017-06-03 09:07:00.000', NULL);
INSERT INTO #tbl ([id], [entrance], [exit])
VALUES (10000, NULL, '2017-06-03 11:59:00.000');
INSERT INTO #tbl ([id], [entrance], [exit])
VALUES (10000, NULL, '2017-06-03 12:31:00.000');
INSERT INTO #tbl ([id], [entrance], [exit])
VALUES (10000, '2017-06-03 12:25:00.000', NULL);
INSERT INTO #tbl ([id], [entrance], [exit])
VALUES (20000, '2017-06-03 13:13:00.000', NULL);
INSERT INTO #tbl ([id], [entrance], [exit])
VALUES (20000, NULL, '2017-06-03 17:39:00.000');
SELECT en.id, en.[entrance], ex.[exit],
DATEDIFF(MINUTE, en.[entrance], ex.[exit]) elapsed_min
FROM #tbl en
JOIN #tbl ex ON en.id=ex.id AND ex.[exit] IS NOT NULL AND ex.[exit] > en.[entrance]
LEFT JOIN #tbl xex ON en.id=xex.id AND xex.[exit] IS NOT NULL
AND xex.[exit] < ex.[exit] AND xex.[exit] > en.[entrance]
WHERE en.entrance IS NOT NULL AND xex.[id] IS NULL;
GO
-- data stored as per comment
CREATE TABLE #tbl2
(
[id] INT NOT NULL,
[type] CHAR(1) NOT NULL,
[timestamp] DATETIME NOT NULL
);
INSERT INTO #tbl2 ([id], [type], [timestamp])
VALUES (10000, 'E', '2017-06-03 09:07:00.000');
INSERT INTO #tbl2 ([id], [type], [timestamp])
VALUES (10000, 'S', '2017-06-03 11:59:00.000');
INSERT INTO #tbl2 ([id], [type], [timestamp])
VALUES (10000, 'S', '2017-06-03 12:31:00.000');
INSERT INTO #tbl2 ([id], [type], [timestamp])
VALUES (10000, 'E', '2017-06-03 12:25:00.000');
INSERT INTO #tbl2 ([id], [type], [timestamp])
VALUES (20000, 'E', '2017-06-03 13:13:00.000');
INSERT INTO #tbl2 ([id], [type], [timestamp])
VALUES (20000, 'S', '2017-06-03 17:39:00.000');
SELECT en.id, en.[timestamp], ex.[timestamp],
DATEDIFF(MINUTE, en.[timestamp], ex.[timestamp]) elapsed_min
FROM #tbl2 en
JOIN #tbl2 ex ON en.id=ex.id AND ex.[type]='S' AND ex.[timestamp] > en.[timestamp]
LEFT JOIN #tbl2 xex ON en.id=xex.id AND xex.[type]='S'
AND xex.[timestamp] < ex.[timestamp] AND xex.[timestamp] > en.[timestamp]
WHERE en.[type]='E' AND xex.[id] IS NULL;
GO
對不起,我沒有告訴,數據庫是SQL 2000 –
停止一切你在做什麼,並升級到支持的版本。只是一些建議。這是4年前結束的生命支持。 – scsimon
數據庫中沒有「行」。除非您指定要訂購的內容,否則該數據將被視爲無序。你有沒有可靠的排序欄(例如最後更新,或標識欄)? –