There is an event capture table that we have which contains different type of events (based on EventTypeId) for multiple assets (based on assetId).
There was an application bug in our code which we fixed recently where the end time was not being captured correctly. And endtime is captured when the "Severity" changes for a given event type and asset. But this was being done incorrectly.
I tried the below query to get the start and end time but due to the repeating duplicates, I am unable to get to the correct data.
The SQL which I currently formulated (took cue from : Calculate time between On and Off Status rows SQL Server)
WITH ReportData
AS (SELECT e.Id [EventId]
,e.AssetId
,e.StartTime
,e.Severity
,e.EventTypeId
,a.Name [AssetName]
,ROW_NUMBER() OVER (PARTITION BY e.AssetId ORDER BY e.StartTime) RowNum
,ROW_NUMBER() OVER (PARTITION BY e.AssetId ORDER BY e.StartTime)
- ROW_NUMBER() OVER (PARTITION BY e.AssetId, e.Severity ORDER BY e.StartTime) AS [Group]
FROM dbo.Event e
JOIN dbo.Asset a
ON a.Id = e.AssetId)
SELECT state1.AssetName
,state1.AssetId
,MIN(state1.StartTime) [START]
,MAX(state2.StartTime) [END]
,DATEDIFF(SS, MIN(state1.StartTime), MAX(state2.StartTime)) [Duration]
,state1.Severity
,state1.EventId
FROM ReportData state1
LEFT JOIN ReportData state2
ON state1.RowNum = state2.RowNum - 1
WHERE state1.Severity = 'Extreme'
AND state2.StartTime IS NOT NULL
AND state1.EventTypeId = 27
GROUP BY state1.AssetName
,state1.AssetId
,state1.Severity
,state1.EventId
,state1.[Group]
ORDER BY MIN(state1.StartTime) DESC;
The duplicates look something like this
Can someone give me the way to calculate the start and end times based on status change (event type and asset change for severity), ignoring the duplicates.
Also if you could give me a query to identify the duplicates so that we can delete it, would be awesome!