I\'d like to write a query that will calculate the total amount of activity that occurred within each 15 minute interval of the day using only timestamps that correspond to acti
The following query will give you each 15-minute increment that contains at least one start time and the total amount (in minutes) of activity for the entire duration that started in that 15-minute increment.
select Date,
Convert( SmallDatetime, Floor( Cast( StartDateTime as float ) * 96.0 ) / 96.0 ) Increment,
Sum( DateDiff( second, StartDateTime, StopDateTime )) / 60 Duration
from Activities
group by Date, Convert( SmallDatetime, Floor( Cast( StartDateTime as float ) * 96.0 ) / 96.0 );
Which returns this:
Date Increment Duration
---------- ------------------- --------
2015-02-02 2015-02-02 07:00:00 25
2015-02-02 2015-02-02 07:15:00 9
2015-02-02 2015-02-02 07:30:00 7
2015-02-02 2015-02-02 08:00:00 9
2015-02-02 2015-02-02 08:15:00 15
2015-02-02 2015-02-02 08:45:00 30
I was just looking into calculating the running total with overflow into the next increment, when a coupla things occurred to me. One is that you're going to need every 15-minute increment during the time of your query, whether any activity starts in it or not. So we would have to use a tally table to ensure every interval is generated, if nothing else, to catch some overflow minutes from the previous interval.
Then, of course, there is tracking the running total with overflow. While this is possible (see https://stackoverflow.com/a/861073/3658753 for a good explanation of how), it hit me that the combination of the two (tally table and running total) is an awful lot of overhead to be performed in SQL. Remember that performing calculations in SQL is many times faster than even the fastest disk access, but performing calculations in any high level language (Java, C++, C# or even scripting languages like Perl) is going to be many times faster than SQL. Plus the maintainability of the SQL solution will be deep in the basement.
So my recommendation at this point is to take the query above and feed it into a good reporting engine or your application and have them perform the additional calculations. Performance-wise, you'll be way ahead.