-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwindow_functions.sql
More file actions
44 lines (39 loc) · 876 Bytes
/
window_functions.sql
File metadata and controls
44 lines (39 loc) · 876 Bytes
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
/*
Purpose:
Demonstrate window functions for analytics without collapsing rows.
*/
-- Rank orders by amount within each customer
SELECT
customer_id,
order_id,
order_amount,
RANK() OVER (
PARTITION BY customer_id
ORDER BY order_amount DESC
) AS order_rank
FROM orders;
-- Running total of spend per customer
SELECT
customer_id,
order_date,
order_amount,
SUM(order_amount) OVER (
PARTITION BY customer_id
ORDER BY order_date
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
) AS running_total
FROM orders;
-- Identify the most recent order per customer
SELECT *
FROM (
SELECT
customer_id,
order_id,
order_date,
ROW_NUMBER() OVER (
PARTITION BY customer_id
ORDER BY order_date DESC
) AS rn
FROM orders
) sub
WHERE rn = 1;