forked from bbrumm/databasestar
-
Notifications
You must be signed in to change notification settings - Fork 0
/
window_functions.sql
83 lines (70 loc) · 1.24 KB
/
window_functions.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
/*
SQL code for the YouTube video on Window Functions
This should work on Oracle, SQL Server, MySQL, and PostgreSQL,
but the data types for the tables may need to be adjusted
*/
/*
Set up data
*/
CREATE TABLE orders (
order_id INT,
order_date DATE,
order_total INT
);
INSERT INTO orders (order_id, order_date, order_total) VALUES
(1, '2020-04-03', 100),
(2, '2020-04-03', 250),
(3, '2020-04-04', 80),
(4, '2020-04-05', 10);
/*
Select data
*/
SELECT
order_id,
order_date,
order_total
FROM orders;
/*
First window function example
*/
SELECT
order_id,
order_date,
order_total,
SUM(order_total) OVER (
ORDER BY order_id ASC
) AS running_total
FROM orders
ORDER BY order_id ASC;
/*
Add more data
*/
INSERT INTO orders (order_id, order_date, order_total) VALUES
(5, '2020-04-03', 120),
(6, '2020-04-04', 90),
(7, '2020-04-04', 50),
(8, '2020-04-04', 15);
/*
Use a partition clause
*/
SELECT
order_id,
order_date,
order_total,
SUM(order_total) OVER (
PARTITION BY order_date
ORDER BY order_id ASC) AS running_total
FROM orders
ORDER BY order_id ASC;
/*
Update the order by clause
*/
SELECT
order_id,
order_date,
order_total,
SUM(order_total) OVER (
PARTITION BY order_date
ORDER BY order_id ASC) AS running_total
FROM orders
ORDER BY order_date ASC;