-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsnowflake_lead_and_lag_functions
79 lines (64 loc) · 2.31 KB
/
snowflake_lead_and_lag_functions
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
Snowflake supports window functions like `LEAD` and `LAG` for analyzing data within a specific window or partition. Here are some use cases demonstrating the usage of `LEAD` and `LAG` functions in Snowflake SQL queries:
1. Comparing Values in Sequential Rows
Assume you have a table named `sales_data` with columns `sale_date` and `revenue`. You want to compare the revenue of the current row with the revenue of the next row using `LEAD` function.
```sql
SELECT
sale_date,
revenue,
LEAD(revenue) OVER (ORDER BY sale_date) AS next_revenue
FROM
sales_data
ORDER BY
sale_date;
```
2. Calculating the Difference Between Current and Previous Values
If you want to find the difference in revenue between the current row and the previous row using `LAG` function:
```sql
SELECT
sale_date,
revenue,
LAG(revenue) OVER (ORDER BY sale_date) AS prev_revenue,
revenue - LAG(revenue) OVER (ORDER BY sale_date) AS revenue_difference
FROM
sales_data
ORDER BY
sale_date;
```
3. Handling Partitions - Calculate Difference per Group
For partitioned data, say you want to find the difference in revenue between the current row and the previous row within each product category:
```sql
SELECT
product_category,
sale_date,
revenue,
LAG(revenue) OVER (PARTITION BY product_category ORDER BY sale_date) AS prev_revenue,
revenue - LAG(revenue) OVER (PARTITION BY product_category ORDER BY sale_date) AS revenue_difference
FROM
sales_data
ORDER BY
product_category, sale_date;
```
4. Predicting Future Values
Suppose you want to forecast sales revenue by comparing the current revenue with the future revenue using `LEAD` function:
```sql
SELECT
sale_date,
revenue,
LEAD(revenue, 1, 0) OVER (ORDER BY sale_date) AS future_revenue_1_month
FROM
sales_data
ORDER BY
sale_date;
```
5. Using Default Values with LEAD or LAG
You can specify default values for the `LEAD` or `LAG` functions, especially helpful for handling NULLs:
```sql
SELECT
sale_date,
revenue,
LEAD(revenue, 1, 0) OVER (ORDER BY sale_date) AS next_revenue_with_default
FROM
sales_data
ORDER BY
sale_date;
```