Here is a recursive CTE solution using a technique that Paul White blogged about in Performance Tuning the Whole Query Plan.
declare @T table
(
Eventdate date index IX_Eventdate clustered,
Val int
);
insert into @T(Eventdate, Val) values
('2012-03-23', 3965),
('2012-03-26', 3979),
('2012-03-27', 3974),
('2012-03-28', 3965),
('2012-03-29', 3967),
('2012-03-30', 3959),
('2012-04-02', 3951),
('2012-04-03', 3961),
('2012-04-04', 3944),
('2012-04-05', 3935),
('2012-04-09', 3901),
('2012-04-10', 3822);
with C as
(
select top(1)
T.Eventdate,
T.Val,
T.Val as PrevVal1,
T.Val as PrevVal2
from @T as T
order by T.eventdate
union all
select T.Eventdate,
T.Val,
T.PrevVal1,
T.PrevVal2
from (
select T.Eventdate,
T.Val,
iif(abs(T.Val - C.PrevVal1) <= 12, C.PrevVal1, T.Val) as PrevVal1,
iif(abs(T.Val - C.PrevVal1) <= 12, null, T.Val) as PrevVal2,
row_number() over(order by T.Eventdate) as rn
from @T as T
inner join C
on C.Eventdate < T.Eventdate
) as T
where T.rn = 1
)
select C.Eventdate,
C.PrevVal2 as Val
from C
order by C.Eventdate
option (maxrecursion 0);
You need to use the OUTPUT parameter, as it is described in the MSDN article:
Given this dummy stored procedure:
CREATE PROCEDURE sp_test AS
RETURN 2
This code will give you the result:
declare @ret int
exec sp_executesql N'exec @ret = sp_test', N'@ret int OUTPUT', @ret = @ret OUTPUT
select @ret as result
result
-----------
2
(1 row(s) affected)
Best Answer
I assumed that "failed" means
passed = 0
.There are some detail missing from the question, i.e. do we need to compare the very last row (when ordered by
sampledate
) with the previously last "failed" row? If yes, then the following query will do:If, on the other side, we want to compare the last "failed" row with the previous "failed" row, then we could uncomment the
where failed = 0
line above or use the less complicated, just find the last 2 failed rows and compare their levels with a simplegroup by
: