0

有没有办法根据'DOWN'和'UP'值计算同一列中的行之间的SQL时间差,如下所示:

在此处输入图像描述

有3种情况(我知道):

  • Yellow、Orange和Green:有一个state_id 2(down),之后有一个state_id 5(up),所以需要计算两行之间的时间差;
  • 蓝色:state_id 2(down)有多个,state_id 5(up)有多个,所以需要计算第一行和最后一行的时间差;
  • 红色:只有一个state_id 2(down),因为有任何更新还是down,所以需要计算到月底的时间差。

我希望你能帮助我。

4

3 回答 3

1

首先考虑为此使用LAG

但是使用累积 SUM,MIN 的窗口版本也适用于 2 次以上的 DOWN:

-- test reference data
declare @State table (id int, state varchar(4));
insert into @State (id, state) values 
(2,'DOWN'),
(5,'UP')

-- test data, using a table variable
declare @AlertState table (alert_id int identity(1,1), host_id int, state_time datetime, state_id int);
insert into @AlertState (host_id, state_time, state_id) values 
(119, GetDate()-0.32, 2),
(119, GetDate()-0.31, 5),
(119, GetDate()-0.24, 2),
(119, GetDate()-0.23, 2),
(119, GetDate()-0.22, 2),
(119, GetDate()-0.21, 5),
(119, GetDate()-0.15, 5),
(119, GetDate()-0.11, 2);

-- The query
select alert_id, host_id, state_time, state_id,
 diff_min = (
   case 
   when state_id = 5 then 
     datediff(minute, min(state_time) over (partition by host_id, stategroup), state_time)
   when state_id = 2 and stategroup is null then
     datediff(minute, state_time, cast(EOMONTH(GetDate()) as datetime)+1)
   end),
 s.state
from (
    select alert_id, host_id, state_time, state_id,
    sum(case state_id when 5 then 1 end) over (partition by host_id order by state_time desc) as stategroup
    from @AlertState
    where state_id in (2,5)
) q
left join @State s on s.id = q.state_id
order by state_time, alert_id;
于 2017-06-01T16:34:13.497 回答
0

我以前这样做的方式是

Select a.state_time as downtime, 
    (
        select min(inner.state_time) from tablename downentry where
        inner.state_time > outer.state_time and downentry.state='UP'
    ) as uptime

from tablename upentry 
where state = 'DOWN'

然后你需要找到它们之间的日期差异,如果正常运行时间为空,则停机时间和'endofmonth'之间的日期差异

它的性能可能很差,所以我总是将答案写到数据仓库中,但认为它给出了您所要求的结果。

于 2017-06-01T15:20:19.623 回答
0

SQL2012+

您可以尝试以下解决方案:

SELECT y.group_id, host_id = MIN(host_id), start_time = MIN(state_time), end_time = MAX(state_time), diff_minute = DATEDIFF(MINUTE, MIN(state_time), MAX(state_time))
FROM (
    SELECT *, group_id = SUM(x.new_group_start) OVER(ORDER BY x.host_id, x.state_time)
    FROM (
        SELECT  *, new_group_start = IIF(a.state_id = 'DOWN' AND ISNULL(LAG(a.state_id) OVER(ORDER BY a.host_id, a.state_time), 'UP') = 'UP', 1, 0)
        FROM    @Alerts a
    ) x
) y
GROUP BY y.group_id
ORDER BY y.group_id

演示

于 2017-06-01T17:32:16.833 回答