declare @t table
(
Timestamp time,
PSI smallint,
Temp smallint,
index clidx clustered(Timestamp)
--id int identity,
--primary key clustered(Timestamp, id)
);
insert into @t(Timestamp, PSI, Temp)
values
('01:01:01', 59, 264),
('01:01:02', 63, 247),
('01:01:03', 56, 245),
('01:01:04', 64, 262),
('01:01:05', 50, 245),
('01:01:06', 57, 244),
('01:01:07', 64, 251),
('01:01:08', 60, 259),
('01:01:09', 52, 244),
('01:01:10', 52, 242),
('01:01:11', 63, 259),
('01:01:12', 56, 241),
('01:01:13', 51, 252),
('01:01:14', 52, 261),
('01:01:15', 50, 265),
('01:01:16', 54, 251),
('01:01:17', 59, 243),
('01:01:18', 64, 240),
('01:01:19', 55, 265);
select *, case when l.totalrows = 5 and l.minPSI > 50 and l.minTemp > 240 then 1 else 0 end as AlertYN
from @t as t
cross apply
(
select min(p.PSI) as minPSI, max(p.PSI) as maxPSI, min(p.Temp) as minTemp, max(p.Temp) as maxTemp, count(*) as totalrows
from @t as p
where p.TimeStamp > dateadd(second, -5, t.TimeStamp) --check for last 5 secs
and p.TimeStamp <= t.TimeStamp
) as l
--where l.minPSI > 50 and l.minTemp > 240