聚合函數經常需要一個額外的GROUP BY語句。
在GROUP BY語句
在GROUP BY語句與合計函數組的結果集由一個或多個列一起使用。
SQL GROUP BY語法
SELECT column_name, aggregate_function(column_name)
FROM table_name
WHERE column_name operator value
GROUP BY column_name;
演示數據庫
在本教程中,我們將使用眾所周知的Northwind示例數據庫。
下面是從選擇"Orders"表:
訂單ID | 客戶ID | 員工ID | 訂購日期 | ShipperID |
---|---|---|---|---|
10248 | 90 | 5 | 1996-07-04 | 3 |
10249 | 81 | 6 | 1996-07-05 | 1 |
10250 | 34 | 4 | 1996-07-08 | 2 |
而從選擇"Shippers"表:
ShipperID | ShipperName | 電話 |
---|---|---|
1 | Speedy Express | (503) 555-9831 |
2 | United Package | (503) 555-3199 |
3 | Federal Shipping | (503) 555-9931 |
而從選擇"Employees"表:
員工ID | 姓 | 名字 | 生日 | 照片 | 筆記 |
---|---|---|---|---|---|
1 | Davolio | Nancy | 1968-12-08 | EmpID1.pic | Education includes a BA.... |
2 | Fuller | Andrew | 1952-02-19 | EmpID2.pic | Andrew received his BTS.... |
3 | Leverling | Janet | 1963-08-30 | EmpID3.pic | Janet has a BS degree.... |
SQL GROUP BY示例
現在,我們要找出每個托運人發出的訂單數。
下面的SQL語句算作托運人分組的訂單:
例
SELECT Shippers.ShipperName,COUNT(Orders.OrderID) AS NumberOfOrders FROM
Orders
LEFT JOIN Shippers
ON Orders.ShipperID=Shippers.ShipperID
GROUP BY ShipperName;
試一試»
GROUP BY多個列
我們還可以使用GROUP BY語句對多個列,就像這樣:
例
SELECT Shippers.ShipperName, Employees.LastName,
COUNT(Orders.OrderID) AS
NumberOfOrders
FROM ((Orders
INNER JOIN Shippers
ON
Orders.ShipperID=Shippers.ShipperID)
INNER JOIN Employees
ON
Orders.EmployeeID=Employees.EmployeeID)
GROUP BY ShipperName,LastName;
試一試»