I’ve seen some examples of this done, but I can’t seem to get it working right..
I have a table as follows
ID | FK | Location | StartDateTime | EndDateTime
It is a stay segment table. The FK relates to the parent record, and the ID relates to each stay segment. I want to split each stay segment into hourly segments.. So as follows;
If the start time is 10:23 then the first record will be
1 | 254 | Loc1 | 10:23 | 10:59
1 | 254 | Loc1 | 11:00 | 11:59
1 | 254 | Loc1 | 12:00 | 12:45
2 | 254 | Loc2 | 12:45 | 12:50
Your help is appreciated.
There may be various approaches to solving this, like a recursive CTE (if you are on ‘2005+ version), a numbers table, a calendar table (which may also be considered as special case numbers table method).
The following example uses a system table called
master..spt_valuesacting as a plain old numbers table:Because I’m not sure about the time granulation in your data, I defined
HourlyEndDateTimeas “3 milliseconds to the end of the current hour”. You may well change it to “1 second or 1 minute to the end of the hour”.