Goal: Return a dataset showing time differences between successive events of the same type
Table Structure:
CREATE TABLE [dbo].[Event](
[EventID] [int] IDENTITY(1,1) NOT NULL,
[JobID] [int] NOT NULL, --FK to Job Table
[LastRun] [datetime] NOT NULL,
[LastRunEnd] [datetime] NULL,
[LastRunResult] [int] NOT NULL, --FK to Result
) ON [PRIMARY]
--Event ID is PK
Since the data comes from sequential events, LastRun will always increase for each job.
LastRunEnd could be null if the process that creates the entry fails fatally before generating the data.
LastRun will always be greater than all previous LastRunEnd
I'm trying to write a TSQL query that shows for each entry, the JobID, the LastRun and the LastRun of the previous entry. This will give me the gap between the two, and will thus detect missed runs.
My best shot so far:
select this.EventId as thisEvent,prev.Eventid as prevEvent,
this.lastrun as thisRun,
prev.LastRun as prevRun,
datediff(hh,prev.LastRun,this.lastrun) as gap
from Event this
join (select
EventID, JobID,LastRun from Event ) prev on prev.jobid =
this.jobid and prev.EventID = (Select max(EventID) from Event
where LastRun < This.LastRun)
where this.LastRun > '2016-08-01' and job.jobid = 57
This seems to work for the rows it returns, however it returns too few rows. Using the where clause given, there are 15 events. I expected 14 rows returned, but there were only 3. The three that were returned looked like this:
thisEvent prevEvent thisRun prevRun gap
----------- ----------- ---------------- ---------------- ----
5172 5239 2016-08-01 16:16 2016-05-31 15:45 1489
5174 5239 2016-08-02 15:45 2016-05-31 15:45 1512
5176 5239 2016-08-03 15:45 2016-05-31 15:45 1536
I expected something like this:
thisEvent prevEvent thisRun prevRun gap
----------- ----------- ---------------- ---------------- ----
5176 5174 2016-08-03 15:45 2016-08-02 15:45 24
5174 5172 2016-08-02 15:45 2016-08-01 16:16 23
Clearly, all rows are picking up the same previous event. I'm also at a loss as to why only 3 rows are returned
Any help would be appreciated...