-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstripe_7dayavg.sql
More file actions
88 lines (83 loc) · 2.86 KB
/
stripe_7dayavg.sql
File metadata and controls
88 lines (83 loc) · 2.86 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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
CREATE TABLE user_transactions (
transaction_id int,
user_id int,
amount float,
transaction_date datetime
);
INSERT INTO user_transactions (transaction_id, user_id, amount, transaction_date)
VALUES
(1, 1, 1, '2021-01-01 15:10:10'),
(2, 1, 1, '2021-01-01 15:10:10'),
(3, 1, 1, '2021-01-02 15:10:10'),
(4, 1, 1, '2021-01-02 15:10:10'),
(5, 1, 1, '2021-01-03 15:10:10'),
(6, 1, 1, '2021-01-03 15:10:10'),
(7, 1, 1, '2021-01-04 15:10:10'),
(2, 1, 1, '2021-01-05 15:10:10'),
(3, 1, 1, '2021-01-05 15:10:10'),
(4, 1, 1, '2021-01-06 15:10:10'),
(5, 1, 1, '2021-01-07 15:10:10'),
(6, 1, 1, '2021-01-08 15:10:10'),
(7, 1, 1, '2021-01-08 15:10:10'),
(2, 1, 1, '2021-01-08 15:10:10'),
(3, 1, 1, '2021-01-09 15:10:10'),
(4, 1, 1, '2021-01-10 15:10:10'),
(5, 1, 1, '2021-01-10 15:10:10'),
(6, 1, 1, '2021-01-11 15:10:10'),
(7, 1, 1, '2021-01-12 15:10:10'),
(2, 1, 1, '2021-01-13 15:10:10'),
(3, 1, 1, '2021-01-14 15:10:10'),
(4, 1, 1, '2021-01-14 15:10:10'),
(5, 1, 1, '2021-01-15 15:10:10'),
(6, 1, 1, '2021-01-16 15:10:10');
WITH daily_transactions AS (
SELECT
CAST(transaction_date AS DATE) AS transaction_date,
SUM(amount) AS total_amount
FROM
user_transactions
GROUP BY
transaction_date
)
/*
SELECT
transaction_date,
total_amount,
LAG(total_amount, 7) OVER (
ORDER BY transaction_date
) AS prev_week_amount
FROM
daily_transactions;
*/
SELECT
transaction_date,
total_amount,
AVG(total_amount) OVER (
ORDER BY transaction_date
ROWS BETWEEN 6 PRECEDING AND CURRENT ROW
) AS weekly_rolling_avg
FROM
daily_transactions;
/*
+------------------+--------------+--------------------+
| transaction_date | total_amount | weekly_rolling_avg |
+------------------+--------------+--------------------+
| 2021-01-01 | 2 | 2 |
| 2021-01-02 | 2 | 2 |
| 2021-01-03 | 2 | 2 |
| 2021-01-04 | 1 | 1.75 |
| 2021-01-05 | 2 | 1.8 |
| 2021-01-06 | 1 | 1.6666666666666667 |
| 2021-01-07 | 1 | 1.5714285714285714 |
| 2021-01-08 | 3 | 1.7142857142857142 |
| 2021-01-09 | 1 | 1.5714285714285714 |
| 2021-01-10 | 2 | 1.5714285714285714 |
| 2021-01-11 | 1 | 1.5714285714285714 |
| 2021-01-12 | 1 | 1.4285714285714286 |
| 2021-01-13 | 1 | 1.4285714285714286 |
| 2021-01-14 | 2 | 1.5714285714285714 |
| 2021-01-15 | 1 | 1.2857142857142858 |
| 2021-01-16 | 1 | 1.2857142857142858 |
+------------------+--------------+--------------------+
16 rows in set, 1 warning (0.00 sec)
*/