Zadnych kursorów, to można załatwić zwykłym zapytaniem.
Oczywiście jak pisali u ciebie ID to nie ID a klucz obcy (ID musi być unikalne).
Wiec zapytanie bym zaproponowal takie (w komentarzu masz podane tworzenie tabeli):
/*
–DROP TABLE #TB1
CREATE TABLE #TB1 (
ID INT,
DATA DATETIME
);
INSERT INTO #TB1
SELECT 1,
GETDATE();
WAITFOR DELAY ‘00:00:01’;
INSERT INTO #TB1
SELECT 1,
GETDATE();
WAITFOR DELAY ‘00:00:01’;
INSERT INTO #TB1
SELECT 1,
GETDATE();
WAITFOR DELAY ‘00:00:01’;
INSERT INTO #TB1
SELECT 1,
GETDATE();
WAITFOR DELAY ‘00:00:01’;
INSERT INTO #TB1
SELECT 2,
GETDATE();
WAITFOR DELAY ‘00:00:01’;
INSERT INTO #TB1
SELECT 2,
GETDATE();
WAITFOR DELAY ‘00:00:01’;
INSERT INTO #TB1
SELECT 2,
GETDATE();
WAITFOR DELAY ‘00:00:01’;
INSERT INTO #TB1
SELECT 2,
GETDATE();
WAITFOR DELAY ‘00:00:01’;
INSERT INTO #TB1
SELECT 3,
GETDATE();
WAITFOR DELAY ‘00:00:01’;
INSERT INTO #TB1
SELECT 3,
GETDATE();
WAITFOR DELAY ‘00:00:01’;
INSERT INTO #TB1
SELECT 3,
GETDATE();
WAITFOR DELAY ‘00:00:01’;
INSERT INTO #TB1
SELECT 2,
GETDATE();
WAITFOR DELAY ‘00:00:01’;
INSERT INTO #TB1
SELECT 2,
GETDATE();
WAITFOR DELAY ‘00:00:01’;
INSERT INTO #TB1
SELECT 2,
GETDATE();
WAITFOR DELAY ‘00:00:01’;
INSERT INTO #TB1
SELECT 3,
GETDATE();
WAITFOR DELAY ‘00:00:01’;
INSERT INTO #TB1
SELECT 3,
GETDATE();
WAITFOR DELAY ‘00:00:01’;
INSERT INTO #TB1
SELECT 3,
GETDATE();
WAITFOR DELAY ‘00:00:01’;
INSERT INTO #TB1
SELECT 1,
GETDATE();
WAITFOR DELAY ‘00:00:01’;
INSERT INTO #TB1
SELECT 1,
GETDATE();
WAITFOR DELAY ‘00:00:01’;
INSERT INTO #TB1
SELECT 1,
GETDATE();
*/
DECLARE @ID_MAX INT;
SELECT @ID_MAX = MAX(ID)
FROM #TB1;
WITH DATES_MAX
AS (
SELECT ID,
MAX(DATA) AS T_MAX
FROM #TB1 T1
GROUP BY ID
),
DATES_MIN
AS (
SELECT ID,
MIN(DATA) AS T_MIN
FROM #TB1 T1
GROUP BY ID
)
SELECT T1.ID,
T2.ID,
T1.T_MAX - T2.T_MIN
FROM DATES_MAX T1
JOIN DATES_MIN T2 ON T1.ID = CASE T2.ID
WHEN @ID_MAX
THEN 1
ELSE T2.ID + 1
END