Skip to content

Commit 6cc71f7

Browse files
Update RANGE-clause-in-window-functions-practical-examples.md
1 parent 6c77693 commit 6cc71f7

File tree

1 file changed

+65
-0
lines changed

1 file changed

+65
-0
lines changed

RANGE-clause-in-window-functions-practical-examples.md

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -145,3 +145,68 @@ from page_views
145145
| 2020-01-25 | 20 | b | 22 |
146146
| 2020-03-15 | 2 | b | 22 |
147147
| 2020-05-15 | 2 | b | 2 |
148+
149+
## Example 4. Moving Average. Moving Average (MA) of the 3 weeks Windows of data.
150+
151+
### Input data
152+
153+
|report_date|item_id|brand|cycle_length|
154+
|------------|-----|---------|---|
155+
| 2023-09-13 | 123 | Apple | 6 |
156+
| 2023-09-13 | 500 | Apple | 5 |
157+
| 2023-09-20 | 123 | Apple | 6 |
158+
| 2023-09-20 | 500 | Apple | 5 |
159+
| 2023-09-27 | 123 | Apple | 6 |
160+
| 2023-09-27 | 500 | Apple | 4 |
161+
| 2023-10-04 | 123 | Apple | 6 |
162+
| 2023-10-04 | 500 | Apple | 4 |
163+
| 2023-09-13 | 325 | Samsung | 7 |
164+
| 2023-09-13 | 862 | Samsung | 3 |
165+
| 2023-09-13 | 455 | Samsung | 5 |
166+
| 2023-09-20 | 325 | Samsung | 7 |
167+
| 2023-09-20 | 862 | Samsung | 3 |
168+
| 2023-09-27 | 455 | Samsung | 5 |
169+
| 2023-10-04 | 325 | Samsung | 7 |
170+
| 2023-09-27 | 862 | Samsung | 4 |
171+
| 2023-10-04 | 455 | Samsung | 7 |
172+
| 2023-10-11 | 325 | Samsung | 7 |
173+
| 2023-10-04 | 862 | Samsung | 4 |
174+
| 2023-10-11 | 455 | Samsung | 7 |
175+
176+
### SQL Query
177+
178+
```sql
179+
select
180+
*
181+
, avg(cycle_length) over (partition by brand
182+
order by report_date
183+
range between interval '14 days' preceding and current row
184+
) as brand_avg_cycle_length_3_weeks
185+
from average_cycle
186+
order by brand, report_date;
187+
```
188+
189+
### Query Output
190+
191+
|report_date|item_id|brand|cycle_length|brand_avg_cycle_length_3_weeks|
192+
|------------|-----|---------|---|-------|
193+
| 2023-09-13 | 500 | Apple | 5 | 5.500 |
194+
| 2023-09-13 | 123 | Apple | 6 | 5.500 |
195+
| 2023-09-20 | 123 | Apple | 6 | 5.500 |
196+
| 2023-09-20 | 500 | Apple | 5 | 5.500 |
197+
| 2023-09-27 | 123 | Apple | 6 | 5.333 |
198+
| 2023-09-27 | 500 | Apple | 4 | 5.333 |
199+
| 2023-10-04 | 123 | Apple | 6 | 5.166 |
200+
| 2023-10-04 | 500 | Apple | 4 | 5.166 |
201+
| 2023-09-13 | 455 | Samsung | 5 | 5.000 |
202+
| 2023-09-13 | 862 | Samsung | 3 | 5.000 |
203+
| 2023-09-13 | 325 | Samsung | 7 | 5.000 |
204+
| 2023-09-20 | 325 | Samsung | 7 | 5.000 |
205+
| 2023-09-20 | 862 | Samsung | 3 | 5.000 |
206+
| 2023-09-27 | 455 | Samsung | 5 | 4.857 |
207+
| 2023-09-27 | 862 | Samsung | 4 | 4.857 |
208+
| 2023-10-04 | 325 | Samsung | 7 | 5.285 |
209+
| 2023-10-04 | 455 | Samsung | 7 | 5.285 |
210+
| 2023-10-04 | 862 | Samsung | 4 | 5.285 |
211+
| 2023-10-11 | 325 | Samsung | 7 | 5.857 |
212+
| 2023-10-11 | 455 | Samsung | 7 | 5.857 |

0 commit comments

Comments
 (0)