By using db<>fiddle, you agree to license everything you submit by Creative Commons CC0.
create table mytable (
id int,
Timestamps datetime
);
insert into mytable values
(1 , '2022-09-23 15:01:00'),
(2 , '2022-09-23 15:02:00'),
(3 , '2022-10-03 14:52:00'),
(4 , '2022-10-03 14:53:00'),
(5 , '2022-10-03 14:54:00'),
(6 , '2022-10-03 14:56:00'),
(7 , '2022-10-03 14:57:00'),
(8 , '2022-10-03 14:58:00'),
(9 , '2022-10-03 14:59:00');
9 rows affected
with cte as (
select *, lead(Timestamps) over (order by Timestamps) as lead,
case when
datediff(mi, Timestamps, LEAD(Timestamps) over (order by Timestamps)) = 1 then 0 else 1 end as diff
from mytable
)
select *
from cte
id | Timestamps | lead | diff |
---|---|---|---|
1 | 2022-09-23 15:01:00.000 | 2022-09-23 15:02:00.000 | 0 |
2 | 2022-09-23 15:02:00.000 | 2022-10-03 14:52:00.000 | 1 |
3 | 2022-10-03 14:52:00.000 | 2022-10-03 14:53:00.000 | 0 |
4 | 2022-10-03 14:53:00.000 | 2022-10-03 14:54:00.000 | 0 |
5 | 2022-10-03 14:54:00.000 | 2022-10-03 14:56:00.000 | 1 |
6 | 2022-10-03 14:56:00.000 | 2022-10-03 14:57:00.000 | 0 |
7 | 2022-10-03 14:57:00.000 | 2022-10-03 14:58:00.000 | 0 |
8 | 2022-10-03 14:58:00.000 | 2022-10-03 14:59:00.000 | 0 |
9 | 2022-10-03 14:59:00.000 | null | 1 |
with cte as (
select *, lead(Timestamps) over (order by Timestamps) as lead,
case when
datediff(mi, Timestamps, LEAD(Timestamps) over (order by Timestamps)) = 1 then 0 else 1 end as diff
from mytable
),
cte2 as (
select *, sum(diff) over(order by Timestamps) as grp
from cte
)
select grp+1 as range_id, min(Timestamps) as [From], max(lead) as [To]
from cte2
where lead is not null
group by grp
range_id | From | To |
---|---|---|
1 | 2022-09-23 15:01:00.000 | 2022-09-23 15:02:00.000 |
2 | 2022-09-23 15:02:00.000 | 2022-10-03 14:54:00.000 |
3 | 2022-10-03 14:54:00.000 | 2022-10-03 14:59:00.000 |