Here's the tally table version.
Set up some dummy data:
/*
CREATE TABLE MyTable
(
MyDate DATETIME,
Status varchar(10)
)
INSERT INTO Mytable VALUES ('2009-01-01 12:00:00','OK')
INSERT INTO Mytable VALUES ('2009-01-01 12:03:00','FAILED')
INSERT INTO Mytable VALUES ('2009-01-01 12:04:00','OK')
INSERT INTO Mytable VALUES ('2009-01-01 12:06:20','OK')
INSERT INTO Mytable VALUES ('2009-01-01 12:07:35','FAILED')
INSERT INTO Mytable VALUES ('2009-01-01 12:07:40','FAILED')
INSERT INTO Mytable VALUES ('2009-01-01 12:20:40','FAILED')
INSERT INTO Mytable VALUES ('2009-01-01 12:25:40','OK')
*/
Set up values and paramters. I hard-coded everything for 10 minute intervals, but this too could be a paramter.
DECLARE
@StartAt datetime
,@Through datetime
SET @StartAt = 'Jan 1, 2009'
SET @Through = getdate() -- or whenever
And the query. This lists rows only when there is data to list; make it an inner join to also list "time slots" without activity.
;WITH
-- Itzik Ben-Gan's tally table routine
Pass0 as (select 1 as C union all select 1), --2 rows
Pass1 as (select 1 as C from Pass0 as A, Pass0 as B),--4 rows
Pass2 as (select 1 as C from Pass1 as A, Pass1 as B),--16 rows
Pass3 as (select 1 as C from Pass2 as A, Pass2 as B),--256 rows
Pass4 as (select 1 as C from Pass3 as A, Pass3 as B),--65536 rows
Pass5 as (select 1 as C from Pass4 as A, Pass4 as B),--4,294,967,296 rows
Tally as (select row_number() over(order by C) as Number from Pass5)
(...look up discussions on "tally tables" or "table of numbers" for the what-and-why's behind this...)
select
xx.FromTime
,sum(case when mt.Status = 'OK' then 1 else 0 end) HowManyOk
,sum(case when mt.Status = 'Failed' then 1 else 0 end) HowManyFailed
from (select
dateadd(mi, (Number-1) * 10, @StartAt) FromTime
,dateadd(mi, Number * 10, @StartAt) ThruTime
from Tally where Number <= datediff(mi, @StartAt, @Through) /10) xx
inner join MyTable mt
on mt.MyDate >= xx.FromTime and mt.MyDate < xx.ThruTime
group by xx.FromTime
So my question is: of all the methods presented, which scales better as data volume increases? I hope somebody tests this.