add batch remove batch split batch comment selection show hidden batches hide batch highlight batch
db<>fiddle
donate feedback about
By using db<>fiddle, you agree to license everything you submit by Creative Commons CC0.
DECLARE @t TABLE (id INT, timeOn DATETIME, timeOff DATETIME);
INSERT INTO @t VALUES
(761058840, '2018-01-02 07:54:28.000', '2018-01-02 08:33:34.000'),
(761058840, '2018-01-02 07:54:28.000', '2018-01-02 08:36:30.000'),
(761058840, '2018-01-02 08:33:45.000', '2018-01-02 08:35:30.000'),
(761058840, '2018-01-02 13:11:18.000', '2018-01-02 13:14:04.000'),
(761058840, '2018-01-02 13:11:18.000', '2018-01-02 13:39:40.000'),
(761058840, '2018-01-02 13:22:11.000', '2018-01-02 13:40:25.000'),
(761058840, '2018-01-02 15:56:18.000', '2018-01-02 15:59:34.000'),
(761058840, '2018-01-02 15:56:18.000', '2018-01-02 16:36:25.000'),
(761058840, '2018-01-02 16:01:34.000', '2018-01-02 16:05:34.000'),
(761058840, '2018-01-02 16:33:19.000', '2018-01-02 16:38:26.000'),
(761058840, '2018-01-02 21:20:25.000', '2018-01-02 21:24:25.000'),
(761058840, '2018-01-02 22:20:36.000', '2018-01-03 05:20:37.000'),
(761058840, '2018-01-02 22:20:36.000', '2018-01-03 05:20:37.000'),
(761058840, '2018-01-03 08:31:29.000', '2018-01-03 09:01:10.000'),
(761058840, '2018-01-03 08:31:59.000', '2018-01-03 09:01:07.000'),
(761058840, '2018-01-03 09:01:57.000', '2018-01-03 09:06:27.000'),
(761058840, '2018-01-03 14:07:27.000', '2018-01-03 14:17:32.000'),
(761058840, '2018-01-03 14:09:28.000', '2018-01-03 14:45:00.000'),
(761058840, '2018-01-03 14:19:32.000', '2018-01-03 14:48:22.000'),
(761058840, '2018-01-03 17:30:38.000', '2018-01-03 18:06:35.000'),
(761058840, '2018-01-03 17:33:54.000', '2018-01-03 18:09:48.000');

WITH t_with_change AS (
SELECT id, timeOn, timeOff, CASE WHEN MAX(timeOff) OVER (PARTITION BY ID ORDER BY timeOn ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING) >= timeOn THEN 0 ELSE 1 END AS chg
FROM @t
), t_with_groups AS(
SELECT id, timeOn, timeOff, SUM(chg) OVER (PARTITION BY ID ORDER BY timeOn) AS grp
FROM t_with_change
)
SELECT id, grp, MIN(timeOn) AS timeOn, MAX(timeOff) AS timeOff
FROM t_with_groups
GROUP BY id, grp

id grp timeOn timeOff
761058840 1 02/01/2018 07:54:28 02/01/2018 08:36:30
761058840 2 02/01/2018 13:11:18 02/01/2018 13:40:25
761058840 3 02/01/2018 15:56:18 02/01/2018 16:38:26
761058840 4 02/01/2018 21:20:25 02/01/2018 21:24:25
761058840 5 02/01/2018 22:20:36 03/01/2018 05:20:37
761058840 6 03/01/2018 08:31:29 03/01/2018 09:01:10
761058840 7 03/01/2018 09:01:57 03/01/2018 09:06:27
761058840 8 03/01/2018 14:07:27 03/01/2018 14:48:22
761058840 9 03/01/2018 17:30:38 03/01/2018 18:09:48