动态计算同一行的时差

时间:2017-06-01 15:07:21

标签: sql sql-server datediff availability

有没有办法根据'DOWN'和'UP'这样的值计算同一列中各行之间SQL的时差:

enter image description here

有3种情况(我知道):

  • 黄色,橙色和绿色:有一个state_id 2(向下),然后是state_id 5(向上),所以需要在两行之间计算时差;
  • 蓝色:有多个state_id 2(向下),之后有一个state_id 5(向上),所以需要在第一行和最后一行之间计算时差;
  • 红色:只有一个state_id 2(向下),因为任何更新都会关闭,所以需要计算时差直到月底。

我希望你能帮助我。

3 个答案:

答案 0 :(得分: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;

答案 1 :(得分: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'之间的约会时间

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

答案 2 :(得分: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

<强> Demo