這裏是理貨表版本。
設置一些虛擬的數據:
/*
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')
*/
設置值和paramters。我將所有內容硬編碼了10分鐘,但這也可能是一個參數。
DECLARE
@StartAt datetime
,@Through datetime
SET @StartAt = 'Jan 1, 2009'
SET @Through = getdate() -- or whenever
然後查詢。這僅在存在要列出的數據時才列出行;使其成爲內部連接以列出沒有活動的「時隙」。
;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)
(...在「理貨表」或「號碼錶」中查找討論什麼,和爲什麼這背後...的)
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
所以我的問題是:所有提出的方法,隨着數據量的增加,規模越大?我希望有人測試這個。
你說每隔10分鐘,但例子顯示每15 .. – 2010-02-18 22:39:00