DROP TABLE IF EXISTS #tempPeceni

CREATE TABLE #tempPeceni
(
EventID VARCHAR(8) NOT NULL,
StartDateTime DATETIME NOT NULL,
EndDateTime DATETIME NOT NULL
)



INSERT INTO #tempPeceni
VALUES
('peceni', 'september 17, 2023 7:0:00', 'september 18, 2023 02:26:18');




select hr.ld AS CasDavky, 
   60 - case when e.startdatetime > hr.ld then datepart(minute, e.startdatetime) else 0 end
   + case when e.enddatetime < hr.ud then datepart(minute, e.enddatetime)-60 else 0 end as allocatedminutes
from #tempPeceni as e
cross apply
(
  select
    dateadd(hour, datepart(hour,e.startdatetime)+t.rn-1, cast(cast(e.startdatetime as date) as datetime)) as ld, 
    dateadd(hour, datepart(hour,e.startdatetime)+t.rn, cast(cast(e.startdatetime as date) as datetime)) as ud,
    rn
  from
  (
    -- a tally, max 100 rows .. max 100 hours duration
    select top (1+datediff(hour,e.startdatetime,dateadd(minute, -1, e.enddatetime))) row_number() over(order by @@spid) as rn
    from (values(1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) as a(n)
    cross join (values(1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) as b(n)
  ) as t
) as hr;
