這裏使用CURSOR yuk !!!
示例數據:
IF OBJECT_ID('tempdb..#TEMP') IS NOT NULL
DROP TABLE #TEMP;
CREATE TABLE #TEMP(Id INT,
NodeId INT,
StartTime DATETIME,
NextId INT);
INSERT INTO #TEMP
VALUES
(16, 87771, '2016-02-01 11:01:00', 17),
(17, 87771, '2016-02-01 11:02:00', 18),
(18, 87771, '2016-02-01 11:03:00', 19),
(19, 87771, '2016-02-01 11:05:00', NULL),
(27, 87774, '2016-02-01 08:43:00', 28),
(28, 87774, '2016-02-01 08:44:00', 29),
(29, 87774, '2016-02-01 08:46:00', 30),
(30, 87774, '2016-02-01 08:47:00', NULL),
(40, 87771, '2016-02-01 11:52:00', 41),
(41, 87771, '2016-02-01 11:53:00', 42),
(42, 87771, '2016-02-01 11:55:00', NULL),
(72, 87774, '2016-02-01 10:07:00', 73),
(73, 87774, '2016-02-01 10:08:00', 74),
(74, 87774, '2016-02-01 10:09:00', 75),
(75, 87774, '2016-02-01 10:11:00', 76),
(76, 87774, '2016-02-01 10:13:00', NULL);
QUERY:
-- pull the data into a staging table with an extra column to hold GroupID
IF OBJECT_ID('tempdb..#TEMP2') IS NOT NULL
DROP TABLE #TEMP2;
SELECT *,
CAST(NULL AS INT) AS groupID
INTO #temp2
FROM #TEMP;
-- Unfortunately I cant see any other way except using a cursor put the results into groups. I really hate using cursors but...
DECLARE @NodeId INT,
@id INT,
@nextid INT,
@groupID INT = 1;
DECLARE group_Cursor CURSOR
FOR SELECT NodeId,
Id,
NextId
FROM #TEMP
ORDER BY Id;
OPEN group_Cursor;
FETCH NEXT FROM group_Cursor INTO @NodeId,
@id,
@nextid;
WHILE @@FETCH_STATUS = 0
BEGIN
SELECT @NodeId,
@id,
@nextid;
UPDATE A
SET A.groupID = @groupID
FROM #temp2 AS A
WHERE A.NodeId = @NodeId
AND A.Id = @id;
FETCH NEXT FROM group_Cursor INTO @NodeId,
@id,
@nextid;
IF @nextid IS NULL
SELECT @groupID+=1;
END;
CLOSE group_Cursor;
DEALLOCATE group_Cursor;
-- this is to resolve a bug where it gives groupID an extra increment if nextid IS NULL not sure why that's happening
UPDATE t
SET t.groupID = t.groupID - 1
FROM #temp2 t
WHERE nextid IS NULL;
SELECT t1.NodeId,
SUM(DATEDIFF(SECOND, t1.StartTime, t2.StartTime))
FROM #TEMP2 AS t1
INNER JOIN #TEMP2 AS t2 ON t1.NodeId = t2.NodeId
AND t1.NextId = t2.Id
GROUP BY t1.NodeId,
t1.groupID;
結果:
您是否嘗試過使用DATEDIFF()函數? https://msdn.microsoft.com/en-us/library/ms189794.aspx –