-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path3.3_Expensive_Shipping_Routes.sql
More file actions
64 lines (55 loc) · 1.44 KB
/
3.3_Expensive_Shipping_Routes.sql
File metadata and controls
64 lines (55 loc) · 1.44 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
-- 1. Map every product_id to its factory
WITH
factory_loc AS (
SELECT
p.product_id,
f.factory_name
FROM products p
JOIN factories f
ON p.factory_name = f.factory_name
),
-- 2. Map every ZIP to its city/state & postal code
customer_loc AS (
SELECT
zip AS customer_zip,
u.city AS customer_city,
state_name AS customer_state,
postal_code AS zip
FROM us_zips u
JOIN sales s
ON u.zip = s.postal_code
),
-- 3. Build a sales view with origin & destination
sales_routes AS (
SELECT
s.row_id,
fl.factory_name AS factory,
cl.zip AS customer_zip,
cl.city AS customer_city,
cl.state_name AS customer_state,
s.cost AS shipping_cost
FROM sales s
JOIN products p
ON s.product_id = p.product_id
JOIN factories fl
on p.factory_name = fl.factory_name
JOIN us_zips cl
ON s.postal_code = cl.zip
)
SELECT
factory,
customer_zip,
SUM(shipping_cost) AS total_shipping_cost,
COUNT(*) AS num_orders,
ROUND(AVG(shipping_cost), 2) AS avg_cost_per_order,
customer_state,
customer_city
FROM sales_routes
GROUP BY
factory,
customer_zip,
customer_city,
customer_state
ORDER BY
total_shipping_cost DESC
LIMIT 10;