I have a database table with a Begindate (datetime) and Enddate (datetime). This table contains activity durations. Now I am trying to create a function to calculate the total duration based on non-overlapping activities within a specified begindate-enddate.
An exaple would be as follow:
I am calling upon this function giving the parameters:
Begindate=’2012-08-16 10:00′
Enddate=’2012-08-16 18:00′
Now let’s say the following data is in the table:
- begin: ‘2012-08-15 10:00’ end ‘2012-08-15 14:00’ (total 4 hours)
- begin: ‘2012-08-16 09:00’ end ‘2012-08-16 11:00’ (total 2 hours)
- begin: ‘2012-08-16 10:30’ end ‘2012-08-16 10:45’ (total 15 minutes)
- begin: ‘2012-08-16 12:00’ end ‘2012-08-16 16:00’ (total 4 hours)
- begin: ‘2012-08-16 13:00’ end ‘2012-08-16 17:00’ (total 4 hours)
- begin: ‘2012-08-16 16:30’ end ‘2012-08-16 16:45’ (total 15 minutes)
- begin: ‘2012-08-16 17:30’ end ‘2012-08-16 20:00’ (total 2 hours and 30 minutes)
Now I would love the following to happen:
- The first activity is outside the specified period so will not be included.
- Partial match so this will return 1 hour.
- Activity is inside the second activity so will not be included.
- 4 hours withing the period will be included.
- 1 hour will be included from 16:00 to 17:00
- Activity will not be included.
- Only 30 minutes are inside the specified period so that will be included.
The total returned will be: 6 hours and 30 minutes.
If anyone could help me with this I would be very grateful! 🙂
It might be easier to calculate missing ranges and then substract durations from complete period:
Two ranges overlap if end of first one is after start of second one and start of first one is before end of second one. See the link for (much better) explanation.
If you are not using Sql Server 2005 or newer, you will need to move code inside
withinto derived tables for supplement d1 and supplement d2.And here is Sql Fiddle with example.