Tsql – Splitting time + duration into intervals in t-sql


Does anyone know of a simple method for solving this?

I have a table which consists of start times for events and the associated durations. I need to be able to split the event durations into thirty minute intervals. So for example if an event starts at 10:45:00 and the duration is 00:17:00 then the returned set should allocate 15 minutes to the 10:30:00 interval and 00:02:00 minutes to the 11:00:00 interval.

I'm sure I can figure out a clumsy approach but would like something a little simpler. This must come up quite often I'd imagine but Google is being unhelpful today.



Best Solution

You could create a lookup table with just the times (over 24 hours), and join to that table. You would need to rebase the date to that used in the lookup. Then perform a datediff on the upper and lower intervals to work out their durations. Each middle interval would be 30 minutes.

create table #interval_lookup (
  from_date datetime,
  to_date datetime

declare @time datetime
set @time = '00:00:00'

while @time < '2 Jan 1900'
    insert into #interval_lookup values (@time, dateadd(minute, 30, @time))
    set @time = dateadd(minute, 30, @time)

declare @search_from datetime
declare @search_to datetime

set @search_from = '10:45:00'
set @search_to = dateadd(minute, 17, @search_from) 

  from_date as interval,
    when from_date <= @search_from and 
         @search_from < to_date and 
         from_date <= @search_to and 
         @search_to < to_date 
         then datediff(minute, @search_from, @search_to)
    when from_date <= @search_from and 
         @search_from < to_date 
         then datediff(minute, @search_from, to_date)
    when from_date <= @search_to and 
         @search_to < to_date then 
         datediff(minute, from_date, @search_to)
    else 30
  end as duration
  to_date > @search_from
  and from_date <= @search_to