使用sql查询在同一列中减去两行值的函数?

时间:2017-11-29 01:12:00

标签: sql sql-server

我需要在SQL服务器中编写函数,以便在每个时间记录中在下表中传递MTBFmachine id之后找到上一个time(平均故障间隔时间)。在sql中有类似的帖子来计算MTBF,但在这篇文章中公式是不同的。

假设我有1台服务器机器的数据集。其中,event_type = 0是机器添加时,event_type= 1是机器发生故障时,event_type= 2是机器更新时MTBF = TotalUPTime/number_of_failure

time          machine_id    event_type 
0               3585557842  0
2224028012164   3585557842  1
2224865501808   3585557842  0
2224877592248   3585557842  2
2239280179979   3585557842  2
2258746454424   3585557842  1
2269484103405   3585557842  0
2269484103721   3585557842  2
2499985270969   3585557842  2

要计算UPTIME,我会从time中的第一个event_type = 1中减去time中的event_type=0,依此类推,然后将每个uptime相加{1}},最后将the total UPTIME除以“ CURRENT 失败次数。 当前表示此时间段内的故障,而不是所有故障次数。如果机器有10个故障,那么所有故障数都是10,如果我在时间5需要MTBF,那么我计算直到时间5的正常运行时间,然后除以故障次数直到时间5。

每个记录的预期MTBF是

time            machine_id  event_type  Previous MTBF
0               3585557842    0           0
2224028012164   3585557842    1           0
2224865501808   3585557842    0      2224028012164
2224877592248   3585557842    2      2224028012164
2239280179979   3585557842    2      2224028012164
2258746454424   3585557842    1      2224028012164
2269484103405   3585557842    0      1145894958698
2269484103721   3585557842    2      1145894958698
2499985270969   3585557842    2      1145894958698

我的功能是传递machine id and anytime参数,然后获取MTBF

ALTER function FnGetMTBF(@mach_id bigint, @actualTime bigint)
RETURNS float
AS
BEGIN

declare @MTBF float
declare @timelastfailurehappen float
declare @timelastaddhappen  float
declare @nmbfailure   float
declare @totaluptime float

set @MTBF = 0


-- GET THE TOTAL TIME OF FAILUER 
set @timelastfailurehappen =(
select sum(time) 
from machine_events 
where machine_id = @mach_id and event_type =1 and [time] <= @actualTime )

-- GET THE TOTAL TIME OF ADDING MACHINE INTO DATACENTER 
set @timelastaddhappen =(
select sum(time) 
from machine_events 
where machine_id = @mach_id and event_type =0 and [time] <= @actualTime )

---- GET THE TOTAL NUMBER OF FAILURE  
set @nmbfailure = (select count(*) as numberoffailuer from machine_events where  machine_id = @mach_id and event_type =1 and [time] <= @actualTime )

-- MAKE THE CALCULATION ONLY OF PAIR OF FAILURE AND ADDING, DO NOT SUBTRACT TIME FAILURE WITH FUTURE TIME ADDING OR WITH TIME ADDING THAT NOT HAPPEN BEFORE FAILURE
if (@timelastfailurehappen > @timelastaddhappen)
-- SUM UP THE UPTIME 
set @totaluptime = + (@timelastfailurehappen - @timelastaddhappen) 
-- GET MTBF
set @MTBF =  @totaluptime/ @nmbfailure

return @MTBF
END

0 个答案:

没有答案