I have a database that contains Event data. These Events represent a warning state in a system. They have a StartTime, EndTime, Duration (in seconds) and VarName (and some other attributes that are less relevant for the question).
I am trying to write a query that will allow me to represent the amount of time that a certain warning was active per day. This way, service engineers can easily see if certain changes/fixes caused a warning to decrease or disappear over time.
A quick-and-dirty first attempt is shown below.
SELECT
[VarName] AS metric,
SUM([Duration]) AS value,
Convert(date, [StartTime]) AS date
FROM [dbo].[Events]
WHERE VarName LIKE 'WARN%'
GROUP BY Convert(date, [StartTime]), VarName
ORDER BY date
This works well enough when Events last only a short time and handles multiple Events of the same type in a day. But it breaks down when Events span multiple days (or even weeks).
Example:
| VarName | StartTime | EndTime | Duration |
|---|---|---|---|
| WARN_1 | 2021-06-28 23:00:00.000 | 2021-06-29 02:00:00.00 | 10800 |
What I get:
| metric | date | value |
|---|---|---|
| WARN_1 | 2021-06-28 | 10800 |
What I want:
| metric | date | value |
|---|---|---|
| WARN_1 | 2021-06-28 | 3600 |
| WARN_1 | 2021-06-29 | 7200 |
Taking into account that:
- An event can occur multiple times in the same day
- An event can span multiple days
I'll be fiddling with this today and if I come up with a working solution I'll append it to this post. But I don't work with SQL all that often, and it feels like this may require some more advanced trickery. Any help is appreciated!