-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path01_over.sql
114 lines (50 loc) · 1.37 KB
/
01_over.sql
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
-- region Intern task completed
SELECT DISTINCT
department,
count(*) OVER (PARTITION BY department) AS count_dep,
jobtitle,
count(*) OVER (PARTITION BY jobtitle) AS count_title
FROM humanresources.vemployeedepartment
ORDER BY department;
-- endregion
-- region FRAMING explained
SELECT
letter,
count(*) OVER (),
ROW_NUMBER() OVER ()
FROM regexp_split_to_table('a a a b c c d e', E'\\s+') letter;
-- endregion
-- region aggregations in frames
SELECT
n,
lag(n) OVER (ORDER BY n) AS previous_record,
SUM(n) OVER (ORDER BY n) AS cumulative_sum,
AVG(n) OVER (ORDER BY n) AS moving_avg
FROM
(VALUES (1), (2), (3), (4), (5)) x(n)
ORDER BY n;
-- endregion
-- region Real example) Employee progress
SELECT
fullname,
fiscalyear,
salestotal
FROM sales.vsalespersonsalesbyfiscalyearsdata person_sales;
--
SELECT
fullname,
fiscalyear,
salestotal,
salestotal - lag(salestotal) OVER (PARTITION BY fullname ORDER BY fiscalyear) AS diff
FROM sales.vsalespersonsalesbyfiscalyearsdata person_sales
ORDER BY fullname, fiscalyear;
-- endregion
-- region Real example) Employee progress - deviation from norm
SELECT
fullname,
salestotal,
fiscalyear,
salestotal - avg(salestotal) OVER (PARTITION BY fiscalyear) AS diff_from_avg
FROM sales.vsalespersonsalesbyfiscalyearsdata
ORDER BY fullname, fiscalyear;
-- endregion