See if this works:set nocount ondeclare @yourTable table (ID int, DATESTAMP datetime, DURATION int, DESCRIPTION varchar(30), CHANNEL int)insert @yourTableselect 1, '2008-11-28 12:42:25.000', 27, 'Document delivered.', 7 union allselect 2, '2008-11-28 12:46:12.000', 14, 'Document delivered.', 7 union allselect 3, '2008-11-28 12:47:52.000', 15, 'Document delivered.', 7 union allselect 4, '2008-11-28 12:49:32.000', 14, 'Document delivered.', 7 union allselect 5, '2008-11-28 12:49:33.000', 15, 'Document delivered.', 8 union allselect 6, '2008-11-28 12:53:13.000', 15, 'Document delivered.', 6declare @start datetime ,@numDays intselect @start = '2008-11-28' ,@numDays = 14;with cteas(select id ,datestamp st ,dateadd(second, duration, datestamp) ed ,channelfrom @yourTable)select dateadd(day, datediff(day, 0, a.st), 0) dy ,dateadd(hour, datediff(hour, 0, a.st), 0) hr ,count(*) * 2 [simul_count]from cte ainner join cte b on b.st >= a.st and b.st <= a.ed and b.channel != a.channelwhere a.st >= @startand a.st <= dateadd(day, @numDays, @start)group by dateadd(day, datediff(day, 0, a.st), 0) ,dateadd(hour, datediff(hour, 0, a.st), 0)output:dy hr simul_count----------------------- ----------------------- -----------2008-11-28 00:00:00.000 2008-11-28 12:00:00.000 2
EDIT:modified based on OP request (below)Be One with the OptimizerTG