📅  最后修改于: 2023-12-03 14:44:55.961000             🧑  作者: Mango
在Oracle数据库中,可以使用JOIN语句连接多个表。在此过程中,您可以使用GROUP BY语句将结果按列进行分组。
以下是如何使用SQL语句连接三个表并按列分组的步骤:
在本例中,我们将创建三个表:顾客(Customers)、订单(Orders)和订单详情(OrderDetails)。在创建这些表之前需要确保已经创建了所需要的数据库。
CREATE TABLE Customers (
CustomerID INT PRIMARY KEY,
CustomerName VARCHAR(50),
Address VARCHAR(50),
City VARCHAR(50)
);
CREATE TABLE Orders (
OrderID INT PRIMARY KEY,
CustomerID INT,
OrderDate DATE
);
CREATE TABLE OrderDetails (
OrderDetailID INT PRIMARY KEY,
OrderID INT,
ProductName VARCHAR(50),
Quantity INT
);
INSERT INTO Customers (CustomerID, CustomerName, Address, City)
VALUES (1, 'John', '123 Main St', 'New York');
INSERT INTO Customers (CustomerID, CustomerName, Address, City)
VALUES (2, 'Sally', '456 Maple St', 'San Francisco');
INSERT INTO Orders (OrderID, CustomerID, OrderDate)
VALUES (101, 1, '2022-01-01');
INSERT INTO Orders (OrderID, CustomerID, OrderDate)
VALUES (102, 2, '2022-01-02');
INSERT INTO OrderDetails (OrderDetailID, OrderID, ProductName, Quantity)
VALUES (10001, 101, 'Apple', 5);
INSERT INTO OrderDetails (OrderDetailID, OrderID, ProductName, Quantity)
VALUES (10002, 101, 'Banana', 2);
INSERT INTO OrderDetails (OrderDetailID, OrderID, ProductName, Quantity)
VALUES (10003, 102, 'Orange', 3);
现在,我们将使用JOIN语句连接三个表,以获取顾客姓名、产品名称和购买的数量。
SELECT c.CustomerName, od.ProductName, SUM(od.Quantity) AS TotalQuantity
FROM Customers c
INNER JOIN Orders o ON c.CustomerID = o.CustomerID
INNER JOIN OrderDetails od ON o.OrderID = od.OrderID
GROUP BY c.CustomerName, od.ProductName
上述查询将返回以下结果:
| CustomerName | ProductName | TotalQuantity |
|--------------|-------------|---------------|
| John | Apple | 5 |
| John | Banana | 2 |
| Sally | Orange | 3 |
现在,您知道如何使用Oracle SQL连接三个表并按列分组。这对于从多个表中选择数据非常有用,同时在结果中对数据进行汇总。