在SQL中计算失败时间TTF

时间:2017-11-26 19:38:18

标签: sql sql-server

我需要在SQL服务器中编写函数,以便在每个时间记录中找到此表中的上一个TTF(失败时间)

 time       machine_id  event_type  Previous TTF 
0           97957590    0
64082917976 97957590    1
64508629318 97957590    0
94842321864 97957590    1
95269562076 97957590    0
2.33418E+12 97957590    1
2.33458E+12 97957590    0

其他机器event_type=2表示更新,但这不能用于计算

time      machine_id    event_type
0           3585557842  0
2.22403E+12 3585557842  1
2.22487E+12 3585557842  0
2.22488E+12 3585557842  2
2.23928E+12 3585557842  2
2.25875E+12 3585557842  1
2.26948E+12 3585557842  0
2.26948E+12 3585557842  2
2.49999E+12 3585557842  2

其中,event_type = 0是添加机器时,event_type= 1是机器发生故障时 从技术上讲,TTF (time-to-failure)是时间段 向失败事件添加事件(time中的event = 1time中的event = 0中扣除

预期结果如下表所示:

time        machine_id  event_type  Previous TTF
0           97957590    0           0
64082917976 97957590    1           0
64508629318 97957590    0           64082917976
94842321864 97957590    1           64082917976
95269562076 97957590    0           30333692546
2.33418E+12 97957590    1           30333692546
2.33458E+12 97957590    0           2.23891E+12

我的功能是

alter function FnGetTTF(@mach_id bigint, @actualTime bigint)
RETURNS float
AS
BEGIN

declare @TTF float
declare @timelastfailurehappen float
declare @timelastaddhappen  float

select top 1 @timelastfailurehappen= [time] 
from machine_events 
where machine_id = @mach_id and event_type =1 and [time] <= @actualTime 
order by [time] desc

select top 1 @timelastaddhappen =[time] 
from machine_events 
where machine_id = @mach_id and event_type =0 and [time] <= @actualTime 
order by [time] desc

if( @timelastfailurehappen > @timelastaddhappen)
set @TTF = @timelastfailurehappen - @timelastaddhappen 

return @TTF
END

我当前的问题,我的函数只计算TTF a的event_type =1null其他记录值的记录

1 个答案:

答案 0 :(得分:1)

您可以使用窗口功能执行此操作。假设0和1是混合的:

select me.time, me.machine_id, me.event_type,
       (case when event_type = 1
             then lag(ttf, 2, 0) over (partition by machine_id order by time)
             else lag(ttf, 1, 0) over (partition by machine_id order by time)
        end) as prev_ttf
from (select me.*,
             (case when event_type = 1
                   then time - lag(time) over (partition by machine_id order by time)
              end) as ttf
      from machine_events me
     ) me;

如果您的0和1不是交错的,我建议您使用更合适的样本数据集来提出另一个问题。