By using db<>fiddle, you agree to license everything you submit by Creative Commons CC0.
create table OREN_TEMP(TS datetime)
insert into OREN_TEMP(TS)
values
('2019-10-25 06:20:07.000'),
('2019-10-25 06:20:15.000'),
('2019-10-25 06:20:19.000'),
('2019-10-25 06:20:26.000'),
('2019-10-25 06:20:26.000'),
('2019-10-25 06:20:34.000'),
('2019-10-25 06:20:42.000'),
('2019-10-25 06:20:51.000'),
('2019-10-25 06:20:59.000'),
('2019-10-25 06:21:07.000'),
('2019-10-25 06:21:15.000'),
('2019-10-25 06:21:19.000'),
('2019-10-25 06:21:26.000')
select * from OREN_TEMP
TS |
---|
25/10/2019 06:20:07 |
25/10/2019 06:20:15 |
25/10/2019 06:20:19 |
25/10/2019 06:20:26 |
25/10/2019 06:20:26 |
25/10/2019 06:20:34 |
25/10/2019 06:20:42 |
25/10/2019 06:20:51 |
25/10/2019 06:20:59 |
25/10/2019 06:21:07 |
25/10/2019 06:21:15 |
25/10/2019 06:21:19 |
25/10/2019 06:21:26 |
with first_row as (
select top (1) ot.*
from oren_temp ot
order by ts asc
),
cte as (
select ts, 1 as lev
from first_row
union all
select ot.ts, lev + 1
from oren_temp ot join
cte
on ot.ts >= dateadd(second, 20, cte.ts)
)
select lev, min(ts)
from cte
group by lev;
lev | (No column name) |
---|---|
1 | 25/10/2019 06:20:07 |
2 | 25/10/2019 06:20:34 |
3 | 25/10/2019 06:20:59 |
4 | 25/10/2019 06:21:19 |
with first_row as (
select top (1) ot.*
from oren_temp ot
order by ts asc
),
cte as (
select ts, 1 as lev, convert(int, 1) as seqnum
from first_row
union all
select ot.ts, lev + 1, convert(int, row_number() over (partition by lev order by ot.ts)) as seqnum
from oren_temp ot join
cte
on ot.ts >= dateadd(second, 20, cte.ts)
where seqnum = 1
)
select lev, ts, seqnum
from cte
where seqnum = 1
lev | ts | seqnum |
---|---|---|
1 | 25/10/2019 06:20:07 | 1 |
2 | 25/10/2019 06:20:34 | 1 |
3 | 25/10/2019 06:20:59 | 1 |
4 | 25/10/2019 06:21:19 | 1 |