Alternative approach to calculate most used time interval
In the past I have given the advice to break down all date intervals into the smallest part, most often minutes.
Then OP should group by the minute.
-- Prepare sample data
DECLARE @Data TABLE
(
RecID INT IDENTITY(1, 1) PRIMARY KEY CLUSTERED,
CreateDate DATETIME,
DeleteDate DATETIME
)
-- Populate sample data
INSERT @Data
(
CreateDate,
DeleteDate
)
SELECT '2009-01-14 22:33', '2009-01-14 22:35' UNION ALL
SELECT '2009-01-14 22:33', '2009-01-14 22:33' UNION ALL
SELECT '2009-01-14 22:34', '2009-01-14 22:35' UNION ALL
SELECT '2009-01-14 22:35', '2009-01-14 22:35' UNION ALL
SELECT '2009-01-14 22:35', '2009-01-14 22:36' UNION ALL
SELECT '2009-01-14 22:37', '2009-01-14 22:37' UNION ALL
SELECT '2009-01-14 22:39', '2009-01-14 22:39' UNION ALL
SELECT '2009-01-14 22:38', '2009-01-14 22:38' UNION ALL
SELECT '2009-01-14 22:39', '2009-01-14 22:39' UNION ALL
SELECT '2009-01-14 22:41', '2009-01-14 22:41' UNION ALL
SELECT '2009-01-14 22:43', '2009-01-14 22:44' UNION ALL
SELECT '2009-01-14 22:52', '2009-01-14 22:52' UNION ALL
SELECT '2009-01-14 22:53', '2009-01-14 22:53' UNION ALL
SELECT '2009-01-14 22:53', '2009-01-14 22:53' UNION ALL
SELECT '2009-01-14 22:56', '2009-01-14 22:57' UNION ALL
SELECT '2009-01-14 22:57', '2009-01-14 22:57' UNION ALL
SELECT '2009-01-14 22:58', '2009-01-14 22:58' UNION ALL
SELECT '2009-01-14 22:58', '2009-01-14 22:59' UNION ALL
SELECT '2009-01-14 22:59', '2009-01-14 22:59'
DECLARE @From INT,
@To INT
SELECT @From = MIN(DATEDIFF(MINUTE, 0, CreateDate)),
@To = MAX(DATEDIFF(MINUTE, 0, DeleteDate))
FROM @Data
SELECT w.theTime,
COUNT(*)
FROM (
SELECT DATEADD(MINUTE, Number + @From, 0) AS theTime
FROM master..spt_values
WHERE Type = 'P'
AND Number <= @To - @From
) AS w
INNER JOIN @Data AS d ON d.CreateDate <= w.theTime
AND d.DeleteDate >= w.TheTime
GROUP BY w.theTime
ORDER BY COUNT(*) DESC,
w.theTime DESC
Well, sometimes the time interval is too large to hold all minute values, and what if OP all of a sudden decides to break down the calculation into milliseconds?
The problem resembles about date range searching. Most people use
SELECT *
FROM Table1
WHERE Col1 BETWEEN '20090129 00:00:00.000' AND '20090129 23:59:59.997'
What you should use is open-ended search criteria as
SELECT *
FROM Table1
WHERE Col1 >= '20090129'
AND Col1 < '20090130'
The solution for this type of problem can then look something like this
-- Display the gaps