Skip to content

Commit 3516113

Browse files
committed
Moveing Average and Weighted Moving Average
1 parent b875f25 commit 3516113

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
/********** Moving Average *************/
2+
3+
/*
4+
We want to know the hourly cpu utilization.
5+
So we can create a sliding windows to get the average cpu utilization of 1 hour.
6+
In hour case, each log is inserted per 5 minutes. So for 1 hour, we need to gather 12 logs (transactions).
7+
8+
NOTE:
9+
OVER statements basically said order by the event time, then given the current row, go back 12 rows.
10+
With that set of date, apply the average function.
11+
*/
12+
13+
SELECT
14+
event_time, server_id,
15+
AVG(cpu_utilization) OVER (ORDER BY event_time ROWS BETWEEN 12 PRECEDING AND CURRENT ROW) AS hourly_cpu_util
16+
FROM time_series.utilization;
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/********* Weighted Moving Average ************/
2+
3+
/*
4+
The idea is you want to give MORE weight to the MORE RECENT events than the past events.
5+
6+
We want to weight the average temp of last 3 days. so we need to sum up of those last 3 days.
7+
*/
8+
WITH daily_avg_temp AS (
9+
SELECT
10+
DATE_TRUNC('day', event_time) as event_date,
11+
ROUND(AVG(temp_celcius),2) AS avg_temp
12+
FROM time_series.location_temp
13+
GROUP BY DATE_TRUNC('day', event_time)
14+
)
15+
SELECT
16+
event_date, avg_temp,
17+
(SELECT ROUND(avg_temp,2) * 0.5
18+
FROM daily_avg_temp d2
19+
WHERE d2.event_date = d1.event_date - INTERVAL '1' day
20+
) +
21+
(SELECT ROUND(avg_temp,2) * 0.333
22+
FROM daily_avg_temp d3
23+
WHERE d3.event_date = d1.event_date - INTERVAL '2' day
24+
) +
25+
(SELECT ROUND(avg_temp,2) * 0.167
26+
FROM daily_avg_temp d4
27+
WHERE d4.event_date = d1.event_date - INTERVAL '3' day
28+
) AS three_days_weighted_avg_temp
29+
FROM daily_avg_temp d1

0 commit comments

Comments
 (0)