GROUP BY 语句用于结合 Aggregate 函数,根据一个或多个列对结果集进行分组。 SQL GROUP BY 语法 SELECT column_name, aggregate_function(column_name)FROM table_nameWHERE column_name operator valueGROUP BY column_name; 演
GROUP BY 语句用于结合 Aggregate 函数,根据一个或多个列对结果集进行分组。
SQL GROUP BY 语法
SELECT column_name, aggregate_function(column_name)
FROM table_name
WHERE column_name operator value
GROUP BY column_name;
演示数据库
在本教程中,我们将使用众所周知的 Northwind 样本数据库。
下面是选自 "Orders" 表的数据:
CustomerID
EmployeeID
OrderDate
ShipperID
选自 "Shippers" 表的数据:
ShipperName
Phone
选自 "Employees" 表的数据:
LastName
FirstName
BirthDate
Photo
Notes
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;
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!