Skip to content

Commit c90243b

Browse files
Create RANGE-clause-in-window-functions-practical-examples.md
1 parent e173633 commit c90243b

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
RANGE Clause in Window Functions: Practical Examples
2+
3+
RANGE Clause in Window Functions is now available in Snowflake.
4+
5+
# Example 1. Running sum of acquitions in the last 28 days
6+
7+
## Input Table: Acquisitions by Date
8+
9+
| A | 3 | 2019-10-11 |
10+
|---|----|------------|
11+
| A | 5 | 2019-10-08 |
12+
| A | 10 | 2019-10-05 |
13+
| A | 2 | 2019-09-15 |
14+
| A | 1 | 2019-09-09 |
15+
| A | 1 | 2019-09-01 |
16+
| B | 3 | 2019-10-11 |
17+
| B | 2 | 2019-10-08 |
18+
| B | 3 | 2019-10-05 |
19+
| B | 1 | 2019-09-15 |
20+
| B | 4 | 2019-09-09 |
21+
| C | 1 | 2019-10-11 |
22+
| C | 2 | 2019-10-08 |
23+
| C | 1 | 2019-10-05 |
24+
| C | 1 | 2019-09-15 |
25+
| C | 0 | 2019-09-09 |
26+
| C | 4 | 2019-09-01 |
27+
| C | 1 | 2019-08-28 |
28+
29+
## RANGE based Window query to get running sum of acquitions in the last 28 days
30+
31+
```sql
32+
select
33+
*
34+
, sum(qty) over (partition by article
35+
order by date_acquired
36+
range between interval '28 day' preceding and current row
37+
) as sum_qty_28_days
38+
from acquisitions;
39+
```
40+
41+
## Query Output:
42+
43+
| A | 1 | 2019-09-01 | 1 |
44+
|---|----|------------|----|
45+
| A | 1 | 2019-09-09 | 2 |
46+
| A | 2 | 2019-09-15 | 4 |
47+
| A | 10 | 2019-10-05 | 13 |
48+
| A | 5 | 2019-10-08 | 17 |
49+
| A | 3 | 2019-10-11 | 20 |
50+
| C | 1 | 2019-08-28 | 1 |
51+
| C | 4 | 2019-09-01 | 5 |
52+
| C | 0 | 2019-09-09 | 5 |
53+
| C | 1 | 2019-09-15 | 6 |
54+
| C | 1 | 2019-10-05 | 2 |
55+
| C | 2 | 2019-10-08 | 4 |
56+
| C | 1 | 2019-10-11 | 5 |
57+
| B | 4 | 2019-09-09 | 4 |
58+
| B | 1 | 2019-09-15 | 5 |
59+
| B | 3 | 2019-10-05 | 8 |
60+
| B | 2 | 2019-10-08 | 6 |
61+
| B | 3 | 2019-10-11 | 9 |

0 commit comments

Comments
 (0)