How do I compare Timestamp difference between 2 consecutive records?
This is my example:
DECLARE @x TABLE(ProductID INT, SingleRunFailure bit, SampleDate date);
INSERT @x VALUES
(101, 1, '2016-01-01 10:09:19.617'),
(101, 0, '2016-01-05 11:09:19.617'),
(101, 1, '2016-01-07 12:09:19.617'),
(101, 0, '2016-01-09 12:09:19.617'),
(101, 1, '2016-01-15 13:09:19.617'),
(101, 0, '2016-01-17 13:09:19.617'),
(101, 0, '2016-01-29 14:09:19.617'),
(101, 0, '2016-02-02 15:09:19.617');
;WITH cte(ProductID, CCVPassed)
AS
(
SELECT ProductID, CASE WHEN SUM(LastTwoRunsPass) >= 2 THEN 1 ELSE 0 END
FROM (SELECT ProductID, LastTwoRunsPass = CASE WHEN SingleRunFailure = 0 THEN 1 ELSE 0 END,
RowNumber = ROW_NUMBER() OVER(PARTITION BY ProductID ORDER BY SampleDate DESC)
FROM @x) AS aggregation
WHERE RowNumber <= 2
GROUP BY ProductID
)
SELECT * FROM cte;
This returns me a Pass or Fail where SingleRunFailure flag was false on last 2 records. This part works as expected.
I need to add logic where if the SampleDate difference on the last 2 records was less than 15 minutes return True.
Expected response:
ProductID CCVPassed
101 0
This is because the difference between last 2 records is 4 days. If the SampleDate difference between last 2 records was less than 15 minutes CCVPassed would return 1.
Best Answer
This works like this:
ProductID
ordered bySampleDate
(ROW_NUMBER()).SampleDate
which are the last 2 rows of the sample)SampleDate
Query:
SQL Fiddle
Output:
Note:
ProductId
because it supposed you have severalProductId
in your real table.