Я уверен, что вы можете сделать это еще лучше и оптимизировать эту группу подзапросов, но сейчас это то, что я сделал:
Созданная таблица и вставленные значения:
create table myTable (VideoId int, StartTime int, EndTime int, EntityMid char);
insert into myTable values (1001, 1, 2, 'a');
insert into myTable values (1001, 2, 3, 'a');
insert into myTable values (1001, 3, 4, 'a');
insert into myTable values (1001, 7, 8, 'b');
insert into myTable values (1001, 10, 11,'a');
insert into myTable values (1001, 11, 12,'a');
insert into myTable values (1002, 4, 5, 'c');
insert into myTable values (1002, 7, 8, 'c');
И запрос:
select VideoId
, EntityMid
, Durationes
from
(
select VideoId
, EntityMid
, sum(Durationes) Durationes
, seq_nbr
from (
select VideoId
, EntityMid
, Durationes
, sum(new_grp) OVER ( PARTITION BY VideoId ORDER BY VideoId, StartTime) AS seq_nbr
from
(
select VideoId
, EntityMid
, (EndTime - StartTime ) as Durationes
, StartTime
, CASE
WHEN grouped = LAG (grouped) OVER ( PARTITION BY VideoId ORDER BY VideoId, StartTime, EntityMid)
THEN 0
ELSE 1
END AS new_grp
from
(
select VideoId
, EntityMid
, StartTime
, EndTime
, count('1')
, case
when ((LEAD(StartTime, 1) OVER (ORDER BY StartTime))-StartTime) = 1 and VideoId = (LEAD(VideoId, 1) OVER (ORDER BY VideoId)) then 1
when (StartTime - (LAG(StartTime, 1) OVER (ORDER BY StartTime))) = 1 and VideoId = (LAG(VideoId, 1) OVER (ORDER BY VideoId)) then 1
end grouped
from myTable
group by VideoId
, StartTime
, EndTime
, EntityMid
order by VideoId
, StartTime
,EndTime
, EntityMid
) a
) b
) c
group by VideoId
, EntityMid
, seq_nbr
) d;
Скрипка: https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=0b05a3e10942640488b32c5285ec6158