有没有办法根据'DOWN'和'UP'这样的值计算同一列中各行之间SQL的时差:
有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 强>