I'm looking to add some new functionality to an existing application (database is Microsoft SQL 2005). Basically, I'm trying to calculate how many minutes (or seconds) a particular department was "unmanned" for a particular set of date ranges. I'm looking to query the dataset ideally with one statement. I have a routine that loops through the record set, parses it and spits out an answer, but it's pretty ugly. Does anyone have any suggestions on how I can optimise it for readability, using pure SQL - or even any pointers/articles on what I should be looking at, my Googlefu is failing me.
I guess in some ways this is almost like a "free time" search of a calendar, but aggregated.
Here is a mock sample data set to give you an idea of what I'm working with (effectively colleagues clock in, then clock out). I'm using rounding to minutes below for the sake of simplicity, but I'd likely be calculating in seconds.
------------------------------------------------------------------------
| Colleague Id | Department Id | Date In | Date Out |
------------------------------------------------------------------------
| 1 | 1 | 04/01/2010 08:45 | 04/01/2010 11:45 |
| 2 | 1 | 04/01/2010 09:00 | 04/01/2010 12:15 |
| 3 | 1 | 04/01/2010 10:00 | 04/01/2010 12:00 |
| 4 | 1 | 04/01/2010 12:30 | 04/01/2010 17:00 |
| 1 | 1 | 04/01/2010 12:45 | 04/01/2010 17:15 |
| 3 | 1 | 04/01/2010 13:00 | 04/01/2010 17:25 |
| 5 | 2 | ... | ... |
------------------------------------------------------------------------
So for example, if I queried the above table for Department Id = 1, between 04/01/2010 08:30:00 and 04/01/2010 17:30:00, I would expect a result of 35 minutes (or 2100 seconds) of "unmanned time" (this is sum of the time at the start, middle and end of the range that is unmanned).