-
Notifications
You must be signed in to change notification settings - Fork 52
Expand file tree
/
Copy path34-rolling-average-steps.sql
More file actions
60 lines (45 loc) · 1.65 KB
/
34-rolling-average-steps.sql
File metadata and controls
60 lines (45 loc) · 1.65 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
-- working solution:
WITH CTE AS (
SELECT user_id,
date,
AVG(steps) OVER(PARTITION BY user_id ORDER BY date
ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) AS avg_steps,
LAG(date) OVER(PARTITION BY user_id ORDER BY date) AS prev_date,
LAG(date, 2) OVER(PARTITION BY user_id ORDER BY date) AS prev2_date
FROM daily_steps
)
SELECT user_id, date, ROUND(avg_steps) AS avg_steps
FROM CTE
WHERE date - prev_date = 1
and date - prev2_date = 2;
-- not working solutions
-- Solution 1: using ROWS BETWEEN clause and ROW_NUMBER() to filter
WITH CTE as (
SELECT user_id,
date,
AVG(steps) OVER(PARTITION BY user_id ORDER BY date
ROWS BETWEEN 2 PRECEDING and CURRENT ROW) as avg_steps,
ROW_NUMBER() OVER(PARTITION BY user_id ORDER BY date) as rn
FROM daily_steps
)
SELECT user_id, date, ROUND(avg_steps) as avg_steps
FROM CTE
WHERE rn > 2
-- Solution 2: using LAG()
WITH CTE as (
SELECT user_id,
date,
steps,
LAG(date, 1) OVER (PARTITION BY user_id ORDER BY date) as prev_date,
LAG(date, 2) OVER (PARTITION BY user_id ORDER BY date) as prev2_date
FROM daily_steps
)
SELECT user_id,
date,
ROUND(AVG(steps) OVER (PARTITION BY user_id ORDER BY date ROWS BETWEEN 2 PRECEDING AND CURRENT ROW)) AS avg_steps
FROM CTE
WHERE prev_date = date - INTERVAL '1 DAY'
and prev2_date = date - INTERVAL '2 DAY'
-- NOTE: both don't satisfy all the testcases.
-- '1' is failing the last testcase.
-- '2' is giving error in the single inverted comma around INTERVAL.