As in below list, consider a table of tasks with the time when they started to the time when they ended.
I need to find the optimal method/SQL Query to find the top 5 times when maximum number of tasks where running may be with 1 second accuracy or by range
TaskID | StartDateTime | EndDateTime
1 | 2016-04-23 10:29:48.643 | 2016-04-23 10:29:53.077
2 | 2016-04-23 10:32:58.797 | 2016-04-23 10:33:01.643
3 | 2016-04-23 10:36:09.227 | 2016-04-23 10:36:12.270
4 | 2016-04-23 10:46:58.093 | 2016-04-23 10:47:01.863
5 | 2016-04-23 10:53:08.107 | 2016-04-23 10:53:12.683
So the output can be like
DateTime | NoOfTasksRunning
2016-04-23 10:29:48 | 5
2016-04-23 12:29:48 | 4
2016-04-23 10:59:48 | 4
2016-04-23 01:29:48 | 1
Or like
Duration | NoOfTasksRunning
2016-04-23 10:29:48 to 2016-04-23 10:29:58 | 5
2016-04-23 10:39:48 to 2016-04-23 10:59:00 | 4
2016-04-23 01:29:48 to 2016-04-23 02:29:58 | 1
The most obvious answer is to find largest and smallest datetime and loop through each and every second and get counts but that is not the most efficient way to get to it so please dont include that as your answer.(hoping its not the only way)
Note: there is no correlation in data between different tables above. they are just example to give idea of the output needed or in general the output desired.
No SQL version restrictions, just that it has to be MS SQL and no MySQL or oracle queries.