Hi,
I have a table with columns: jobId, timeStamp (for duration per jobId) and tempData. I created a query that calculates 60 second rolling average by jobId. (you can see it at the end of the post)
Where I am struggling is adding two additional rolling averages. Both of them would be 60 second rolling avg, but with different starting points.
One would start from 15 seconds above the current row and the other one would start from 15 seconds below the current row.
So if the current row shows 2022-11-20 01:40:08.590, one measure would show avg 60 seconds back from 2022-11-20 01:39:53.590 and the other would show avg 60 seconds back from 2022-11-20 01:40:23.590.
Also, for the first 60 seconds and for the last 15 seconds of each jobId - there would be no average (just NULL).
Using PRECEDING/FOLLOWING ROWS for calculation will not work, as timestamps are not continuous (there are missing values). Avg has to be based on timestamp value.
Below is the query I have so far for the rolling 60 second avg.
with cte as (
select jobId,
timeStamp,
dateadd(second, -60, timeStamp) AS lowerBound,
tempData
FROM My_Table t
)
select c.jobId,
c.timeStamp,
c.tempData,
avg(m.tempdata) as MovingAvg
from cte c
inner join My_Table m
ON m.jobId = c.jobId
AND m.timeStamp between c.lowerBound and c.timeStamp
group by c.jobId, c.timeStamp, c.tempData, c.lowerBound
order by 1, 2
Any help would be much appreciated!