-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsp_create_master_view.sql
More file actions
66 lines (58 loc) · 1.84 KB
/
Copy pathsp_create_master_view.sql
File metadata and controls
66 lines (58 loc) · 1.84 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
DELIMITER $$
DROP PROCEDURE IF EXISTS sp_create_master_view $$
CREATE PROCEDURE sp_create_master_view()
BEGIN
DROP VIEW IF EXISTS v_sales_master;
CREATE VIEW v_sales_master AS
SELECT
s.order_id,
s.order_date,
s.order_number,
s.order_quantity,
s.year,
s.month,
s.quarter,
s.day_of_week,
s.is_weekend,
-- Customer features
c.customer_id,
c.age,
c.marital_status,
c.gender,
c.annual_income,
c.income_category,
c.total_children,
c.education_level,
c.occupation,
c.homeowner,
-- Product features
p.product_id,
p.product_name,
p.product_color,
p.product_size,
p.product_cost,
p.product_price,
p.profit_margin,
p.price_category,
-- Territory features (from CSV columns)
s.territory_id,
t.Region AS territory_name,
t.Country AS territory_country,
t.Continent AS territory_group,
-- Category features (from CSV columns)
pc.ProductCategoryKey AS category_id,
pc.CategoryName AS category_name,
psc.ProductSubcategoryKey AS subcategory_id,
psc.SubcategoryName AS subcategory_name,
-- Calculated features
(s.order_quantity * p.product_price) AS total_revenue,
(s.order_quantity * p.product_cost) AS total_cost,
(s.order_quantity * p.product_price) - (s.order_quantity * p.product_cost) AS total_profit
FROM sales_clean s
LEFT JOIN customers_clean c ON s.customer_id = c.customer_id
LEFT JOIN products_clean p ON s.product_id = p.product_id
LEFT JOIN territories t ON s.territory_id = CAST(t.SalesTerritoryKey AS UNSIGNED)
LEFT JOIN product_subcategories psc ON p.product_subcategory_id = psc.ProductSubcategoryKey
LEFT JOIN product_categories pc ON psc.ProductCategoryKey = pc.ProductCategoryKey;
END $$
DELIMITER ;