2008-10-08 61 views
2

我有一個包含我的服務器狀態的表求和拆分範圍在一個SQL查詢

create table ServerStatus 
(
    ServerId int, 
    StartTime datetime, 
    Seconds int, 
    [State] char(8) 
) 

我想給定一個開始和結束日期將總結服務器中的每個狀態期間花費的時間查詢時間。我還希望查詢返回服務器花費在未知狀態的時間量。

因此,例如用於以下數據

1 2008-01-01 00:00:00.000 120 broken 
1 2008-01-02 00:00:00.000 120 off  
1 2008-01-03 00:00:00.000 240 burning 
1 2008-01-04 00:00:00.000 60 off  
1 2008-01-05 00:00:00.000 60 off  
2 2008-01-01 00:00:00.000 60 broken 
2 2008-01-02 00:00:00.000 30 off  
2 2008-01-03 00:00:00.000 20 burning 
2 2008-01-04 00:00:00.000 600 off  
3 2007-01-04 00:00:00.000 600 off  
4 2007-12-12 00:00:00.000 999999999 onfire 

提供的範圍。

select @start = dateadd(second, 60, '2008-01-01'), 
@fin = dateadd(second, 60, '2008-01-04') 

我想返回結果:

1 broken  60 
1 burning  240 
1 off   180 
1 unknown  258720 
2 burning  20 
2 off   90 
2 unknown  259090 
4 onfire  259200 

這個問題有所涉及:Combining split date ranges in a SQL query

+0

我們需要更多信息。例如,StartTime是否正好是午夜?有幾天的時間間隔? – 2008-10-08 13:39:33

回答

3

這是我想出了迄今爲止最好的:

declare @start datetime 
declare @fin datetime 

select @start = dateadd(second, 60, '2008-01-01'), @fin = dateadd(second, 60, '2008-01-04') 

select ServerId, State, Total = sum(
    case when StartTime > @start and DateAdd(second, Seconds, StartTime) <= @fin 
     then Seconds 
    when StartTime < @start and DateAdd(second, Seconds, StartTime) <= @fin 
     then DateDiff(second, @start, DateAdd(second, Seconds, StartTime)) 
    when StartTime < @start and DateAdd(second, Seconds, StartTime) >= @fin 
     then DateDiff(second, @start, @fin) 
    else 
     DateDiff(second,StartTime,@fin) 
    end) 
into #t 
from ServerStatus 
where @start < dateadd(second, Seconds, StartTime) 
and @fin > StartTime 
group by ServerId, State 

insert #t 
select ServerId, 'unknown', DateDiff(second, @start, @fin) - sum(Total) 
from #t 
group by ServerId 
having DateDiff(second, @start, @fin) > sum(Total) 

select * from #t 
order by ServerId, State