forked from baldimario/cq
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample_window_functions.sql
More file actions
72 lines (63 loc) · 2.15 KB
/
example_window_functions.sql
File metadata and controls
72 lines (63 loc) · 2.15 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
-- Window Functions Examples
-- Demonstrates ROW_NUMBER, RANK, DENSE_RANK, LAG, LEAD, and aggregate window functions
-- Example 1: Basic ROW_NUMBER
-- Add sequential row numbers ordered by age
SELECT name, age,
ROW_NUMBER() OVER (ORDER BY age) AS row_num
FROM 'data/users.csv'
LIMIT 5;
-- Example 2: RANK and DENSE_RANK
-- Rank users by age (RANK leaves gaps, DENSE_RANK doesn't)
SELECT name, age,
RANK() OVER (ORDER BY age DESC) AS rank,
DENSE_RANK() OVER (ORDER BY age DESC) AS dense_rank
FROM 'data/users.csv'
ORDER BY age DESC
LIMIT 10;
-- Example 3: PARTITION BY
-- Row number within each role group
SELECT role, name, age,
ROW_NUMBER() OVER (PARTITION BY role ORDER BY age DESC) AS role_rank
FROM 'data/users.csv'
ORDER BY role, role_rank;
-- Example 4: LAG - Compare with previous row
-- Show each person's age and the previous person's age
SELECT name, age,
LAG(age) OVER (ORDER BY age) AS prev_age,
age - LAG(age) OVER (ORDER BY age) AS age_diff
FROM 'data/users.csv'
ORDER BY age;
-- Example 5: LEAD - Compare with next row
-- Show each person's age and the next person's age
SELECT name, age,
LEAD(age) OVER (ORDER BY age) AS next_age,
LEAD(age) OVER (ORDER BY age) - age AS age_gap
FROM 'data/users.csv'
ORDER BY age;
-- Example 6: Running Sum
-- Calculate running sum of ages ordered by name
SELECT name, age,
SUM(age) OVER (ORDER BY name) AS running_sum
FROM 'data/users.csv'
ORDER BY name;
-- Example 7: Running Average
-- Calculate running average of ages
SELECT name, age,
AVG(age) OVER (ORDER BY age) AS running_avg
FROM 'data/users.csv'
ORDER BY age;
-- Example 8: Running Count
-- Count how many rows processed so far
SELECT name, age,
COUNT(*) OVER (ORDER BY age) AS running_count
FROM 'data/users.csv'
ORDER BY age;
-- Example 9: Multiple Window Functions
-- Combine multiple window functions in one query
SELECT name, age, role,
ROW_NUMBER() OVER (ORDER BY age) AS overall_rank,
ROW_NUMBER() OVER (PARTITION BY role ORDER BY age) AS role_rank,
LAG(age) OVER (ORDER BY age) AS prev_age,
LEAD(age) OVER (ORDER BY age) AS next_age
FROM 'data/users.csv'
ORDER BY age;