-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path3join.txt
63 lines (41 loc) · 1.51 KB
/
3join.txt
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
CREATE DATABASE ecommerce;
USE ecommerce;
CREATE TABLE customers (
customer_id INT PRIMARY KEY,
first_name VARCHAR(50),
last_name VARCHAR(50),
manager_id INT
);
CREATE TABLE orders (
order_id INT PRIMARY KEY,
customer_id INT,
order_date DATE,
total_amount DECIMAL(10, 2),
FOREIGN KEY (customer_id) REFERENCES customers(customer_id)
);
INSERT INTO customers (customer_id, first_name, last_name, manager_id)
VALUES
(1, 'John', 'Doe', NULL),
(2, 'Jane', 'Smith', 1),
(3, 'Bob', 'Johnson', 1);
INSERT INTO orders (order_id, customer_id, order_date, total_amount)
VALUES
(101, 1, '2023-01-15', 1200.00),
(102, 2, '2023-02-20', 900.00);
SELECT customers.customer_id, customers.first_name, orders.order_id
FROM customers
INNER JOIN orders ON customers.customer_id = orders.customer_id;
SELECT customers.customer_id, customers.first_name, orders.order_id
FROM customers
LEFT JOIN orders ON customers.customer_id = orders.customer_id;
SELECT customer_id, first_name,
(SELECT COUNT(*) FROM orders WHERE orders.customer_id = customers.customer_id) AS order_count
FROM customers;
CREATE VIEW customer_order_totals AS
SELECT c.customer_id, c.first_name, SUM(o.total_amount) AS total_order_amount
FROM customers c
JOIN orders o ON c.customer_id = o.customer_id
GROUP BY c.customer_id, c.first_name;
SELECT c.customer_id, c.first_name, o.order_id, o.total_amount
FROM customers c
JOIN (SELECT * FROM orders WHERE order_date >= '2023-01-01') o ON c.customer_id = o.customer_id;