-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path02-intermediate.sql
More file actions
74 lines (67 loc) · 1.51 KB
/
Copy path02-intermediate.sql
File metadata and controls
74 lines (67 loc) · 1.51 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
67
68
69
70
71
72
73
74
-- Lesson 02: Intermediate SQL
-- Goal: learn GROUP BY, HAVING, CASE, and joins.
-- 1. Sales by region.
SELECT
region,
COUNT(*) AS total_rows,
SUM(sales) AS total_sales,
SUM(profit) AS total_profit
FROM superstore
GROUP BY region
ORDER BY total_sales DESC;
-- 2. Profit by category.
SELECT
category,
SUM(sales) AS total_sales,
SUM(profit) AS total_profit
FROM superstore
GROUP BY category
ORDER BY total_profit DESC;
-- 3. Group filtering with HAVING.
SELECT
state,
SUM(sales) AS total_sales
FROM superstore
GROUP BY state
HAVING SUM(sales) > 50000
ORDER BY total_sales DESC;
-- 4. Classify rows with CASE.
SELECT
order_id,
product_name,
sales,
profit,
CASE
WHEN profit < 0 THEN 'Loss'
WHEN profit = 0 THEN 'Break Even'
ELSE 'Profit'
END AS profit_status
FROM superstore
LIMIT 20;
-- 5. Join sales to the calendar table.
SELECT
p.year_actual,
p.month_name,
COUNT(*) AS total_orders,
SUM(s.sales) AS total_sales
FROM superstore s
JOIN periode p
ON s.order_date = p.date_actual
GROUP BY p.year_actual, p.month_actual, p.month_name
ORDER BY p.year_actual, p.month_actual;
-- 6. Shipping delay by ship mode.
SELECT
ship_mode,
AVG(ship_date - order_date) AS avg_shipping_days
FROM superstore
GROUP BY ship_mode
ORDER BY avg_shipping_days;
-- 7. Top customers by sales.
SELECT
customer_id,
customer_name,
SUM(sales) AS total_sales
FROM superstore
GROUP BY customer_id, customer_name
ORDER BY total_sales DESC
LIMIT 10;