Hi , I have found this thread which is working fine to get the min start datetime and max datetime when there is an overlap between the date time on a given date..but i wanted to use the same and extend it to get the min start datetime and max end datetime when the overlap is not on the same day
for example the last record for Raj should be as it is meaning get the start datetime and end datetime as it since this is not an overlap - but for the record that is above the last record
('Raj' ,'04-01-2020 11:00','04-02-2020 02:30') - this started at 11am and ended at 2.30pm
('Raj' ,'04-01-2020 12:00','04-02-2020 03:30') - this started 12pm and ended at 330
this is an example of overlap where it is not the same day - so here we need just what we did when it was same day - that is we picked the min of start datetime and max of end datetime for that name
could some please help - really appreciate your help
drop table #TestTable
SELECT Name = CONVERT(VARCHAR(10),v.Name)
,StartDT = CONVERT(DATETIME,v.StartDT)
,EndDT = CONVERT(DATETIME,v.EndDT)
INTO #TestTable
FROM (VALUES
('Aman','01-02-2020 04:30','01-02-2020 06:30')
,('Aman','01-02-2020 08:30','01-02-2020 09:30')
,('Aman','01-02-2020 04:40','01-02-2020 05:30')
,('Aman','01-02-2020 04:55','01-02-2020 07:30')
,('Aman','01-02-2020 14:55','01-02-2020 18:30')
,('Aman','01-02-2020 13:40','01-02-2020 15:30')
,('Ram' ,'01-02-2020 04:40','01-02-2020 05:30')
,('Ram' ,'01-02-2020 04:40','01-02-2020 05:30')
,('Raj' ,'04-01-2020 11:00','04-02-2020 02:30')
,('Raj' ,'04-01-2020 12:00','04-02-2020 03:30')
,('Raj' ,'04-01-2020 10:00','04-02-2020 10:30')
)v(Name,StartDT,EndDT)
;
WITH
C1 AS
(
SELECT Name, TS = StartDT, TYPE = +1, E = NULL, S = ROW_NUMBER() OVER(PARTITION BY Name ORDER BY StartDT)
FROM #TestTable
UNION ALL
SELECT Name, TS = EndDT, TYPE = -1, E = ROW_NUMBER() OVER(PARTITION BY Name ORDER BY EndDT), S = NULL
FROM #TestTable
)
,C2 AS
(
SELECT C1.*,
SE = ROW_NUMBER() OVER(PARTITION BY Name ORDER BY ts, type DESC)
FROM C1
)
,C3 AS
(
SELECT Name, TS, GrpNum = FLOOR((ROW_NUMBER() OVER(PARTITION BY Name ORDER BY ts) - 1) / 2 + 1)
FROM C2
WHERE COALESCE(S - (SE - S) - 1, (SE - E) - E) = 0
)
SELECT Name, StartDT = MIN(TS), EndDT = MAX(TS)
FROM C3
GROUP BY Name, GrpNum
ORDER BY Name, GrpNum
;