How to Merge Time Intervals in SQL Server

How to merge time intervals in SQL Server

You can use a recursive CTE to build a list of dates and then count the distinct dates.

declare @T table
(
startDate date,
endDate date
);

insert into @T values
('2011-01-01', '2011-01-05'),
('2011-01-04', '2011-01-08'),
('2011-01-11', '2011-01-15');

with C as
(
select startDate,
endDate
from @T
union all
select dateadd(day, 1, startDate),
endDate
from C
where dateadd(day, 1, startDate) < endDate
)
select count(distinct startDate) as DayCount
from C
option (MAXRECURSION 0)

Result:

DayCount
-----------
11

Or you can use a numbers table. Here I use master..spt_values:

declare @MinStartDate date
select @MinStartDate = min(startDate)
from @T

select count(distinct N.number)
from @T as T
inner join master..spt_values as N
on dateadd(day, N.Number, @MinStartDate) between T.startDate and dateadd(day, -1, T.endDate)
where N.type = 'P'

Merge overlapping time intervals, how?

You may also try this query (once more solutions beside those given by PM 77-1 in the comment above) :

WITH RECURSIVE cte( id, date_start, date_end ) AS
(
SELECT id, date_start, date_end
FROM evento
UNION
SELECT e.id,
least( c.date_start, e.date_start ),
greatest( c.date_end, e.date_end )
FROM cte c
JOIN evento e
ON e.date_start between c.date_start and c.date_end
OR
e.date_end between c.date_start and c.date_end
)
SELECT distinct date_start, date_end
FROM (
SELECT id,
min( date_start) date_start,
max( date_end ) date_end
FROM cte
GROUP BY id
) xx
ORDER BY date_start;

Demo ---> http://www.sqlfiddle.com/#!12/bdf7e/9

however for huge table the performance of this query could be horribly slow, and some procedural approach might perform better.

Combine continuous datetime intervals by type

Since your ranges are continuous, the problem essentially becomes a gaps-and-islands one. If only you had a criterion to help you to distinguish between different sequences with the same t value, you could group all the rows using that criterion, then just take MIN(s), MAX(e) for every group.

One method of obtaining such a criterion is to use two ROW_NUMBER calls. Consider the following query:

SELECT
*,
rnk1 = ROW_NUMBER() OVER ( ORDER BY s),
rnk2 = ROW_NUMBER() OVER (PARTITION BY t ORDER BY s)
FROM @periods
;

For your example it would return the following set:

s           e           t   rnk1  rnk2
---------- ---------- -- ---- ----
2013-01-01 2013-01-02 3 1 1
2013-01-02 2013-01-04 1 2 1
2013-01-04 2013-01-05 1 3 2
2013-01-05 2013-01-06 2 4 1
2013-01-06 2013-01-07 2 5 2
2013-01-07 2013-01-08 2 6 3
2013-01-08 2013-01-09 1 7 3

The interesting thing about the rnk1 and rnk2 rankings is that if you subtract one from the other, you will get values that, together with t, uniquely identify every distinct sequence of rows with the same t:

s           e           t   rnk1  rnk2  rnk1 - rnk2
---------- ---------- -- ---- ---- -----------
2013-01-01 2013-01-02 3 1 1 0
2013-01-02 2013-01-04 1 2 1 1
2013-01-04 2013-01-05 1 3 2 1
2013-01-05 2013-01-06 2 4 1 3
2013-01-06 2013-01-07 2 5 2 3
2013-01-07 2013-01-08 2 6 3 3
2013-01-08 2013-01-09 1 7 3 4

Knowing that, you can easily apply grouping and aggregation. This is what the final query might look like:

WITH partitioned AS (
SELECT
*,
g = ROW_NUMBER() OVER ( ORDER BY s)
- ROW_NUMBER() OVER (PARTITION BY t ORDER BY s)
FROM @periods
)
SELECT
s = MIN(s),
e = MAX(e),
t
FROM partitioned
GROUP BY
t,
g
;

If you like, you can play with this solution at SQL Fiddle.

Merging date intervals in SQL Server

It takes longer for me to set up the sample data than to write the query - it would be better if you posted questions that include CREATE TABLE and INSERT/SELECT statements. I don't know what your table is called, I've called mine Periods:

create table Periods (
StartDate date not null,
EndDate date not null
)
go
insert into Periods(StartDate,EndDate)
select '19820302','19820930' union all
select '19821001','19850117' union all
select '19850626','19850726' union all
select '19850730','19911231' union all
select '19920101','19951231' union all
select '19960101','20040531' union all
select '20040605','20060131' union all
select '20060201','20110520'
go
; with MergedPeriods as (
Select p1.StartDate, p1.EndDate
from
Periods p1
left join
Periods p2
on
p1.StartDate = DATEADD(day,1,p2.EndDate)
where
p2.StartDate is null
union all
select p1.StartDate,p2.EndDate
from
MergedPeriods p1
inner join
Periods p2
on
p1.EndDate = DATEADD(day,-1,p2.StartDate)
)
select StartDate,MAX(EndDate) as EndDate
from MergedPeriods group by StartDate

Result:

StartDate   EndDate
1982-03-02 1985-01-17
1985-06-26 1985-07-26
1985-07-30 2004-05-31
2004-06-05 2011-05-20

SQL time data merging 30 minute intervals that span a time range per person per activity - time card

I think I have this sussed, admittedly it's not pretty and no doubt a more elegant solution will be along, however the following gives you the desired results using window functions to look at the previous row data.

(note my date format is DMY)

Test data

create table test (EmpNo int, Activity varchar(10), AStart datetime, AEnd datetime)

insert into test
select 1 EmpNo, 'Login' Activity,'17/3/2021 09:18:37' Astart,'17/3/2021 09:26:54 ' AEnd union all
select 1, 'Break','17/3/2021 10:43:25','17/3/2021 10:58:07 ' union all
select 1, 'Lunch','17/3/2021 13:23:02','17/3/2021 13:30:00 ' union all
select 1, 'Lunch','17/3/2021 13:30:00','17/3/2021 14:00:00 ' union all
select 1, 'Lunch','17/3/2021 14:00:00','17/3/2021 14:08:00 ' union all
select 1, 'Break','17/3/2021 17:16:23','17/3/2021 17:30:00 ' union all
select 1, 'Break','17/3/2021 17:30:00','17/3/2021 17:31:00 ' union all
select 1, 'Logout','17/3/2021 19:14:05','17/3/2021 19:16:02 ' union all
select 2, 'Login','17/3/2021 09:03:05','17/3/2021 09:05:02 ' union all
select 2, 'Break','17/3/2021 10:29:02','17/3/2021 10:30:00 ' union all
select 2, 'Break','17/3/2021 10:30:00','17/3/2021 10:44:19 ' union all
select 2, 'Lunch','17/3/2021 13:31:05','17/3/2021 14:00:00 ' union all
select 2, 'Lunch','17/3/2021 14:00:00','17/3/2021 14:15:00 ' union all
select 2, 'Break','17/3/2021 17:30:00','17/3/2021 17:45:00 ' union all
select 2, 'Logout','17/3/2021 19:15:00','17/3/2021 19:16:00 '

Results

with spans as (select *, Iif(Lead(activity,1) over(partition by empno order by Astart)=Activity,0,1) span from test),
ranges as (
select *,
case when IsNull(Lag(activity,1) over (partition by Empno order by AStart),'') ! =Activity then AStart end ActivityStart,
case when span=1 then AEnd end ActivityEnd
from spans s
)

select EmpNo, Activity, ActivityStart, ActivityEnd
from (
select EmpNo, Activity, AStart, IsNull(ActivityStart,Lag(ACtivityStart,1) over(partition by empno order by Astart)) ActivityStart, ActivityEnd
from ranges r
where ActivityStart is not null or span=1
)x
where ActivityEnd is not null

Merge overlapping dates in SQL Server

SQL DEMO

declare @t table (Name varchar(100),  Datetime_Start  datetime,  Datetime_End datetime);
insert into @t values
('A' , '2017-01-02 00:00' , '2017-03-28 00:10'),
('A' , '2017-05-14 23:50' , '2017-05-29 23:50'),
('B' , '2017-05-18 00:00' , '2017-05-18 04:00'),
('B' , '2017-05-18 02:00' , '2017-05-18 03:00'),
('C' , '2017-01-02 00:00' , '2017-01-17 15:50'),
('C' , '2017-01-14 03:50' , '2017-01-28 15:50');

with Datetime_Starts as
(
select distinct name, Datetime_Start
from @t as t1
where not exists
(select * from @t as t2
where t2.name = t1.name
and t2.Datetime_Start < t1.Datetime_Start
and t2.Datetime_End >= t1.Datetime_Start)
),
Datetime_Ends as
(
select distinct name, Datetime_End
from @t as t1
where not exists
(select * from @t as t2
where t2.name = t1.name
and t2.Datetime_End > t1.Datetime_End
and t2.Datetime_Start <= t1.Datetime_End)
)

select name, Datetime_Start,
(select min(Datetime_End)
from Datetime_Ends as e
where e.name = s.name
and Datetime_End >= Datetime_Start) as Datetime_End
from Datetime_Starts as s;


Related Topics



Leave a reply



Submit