自强学堂
自强学堂:学习、分享、让你更强!
SQL 教程HTMLCSSJAVASCRIPTJQUERYSQLPHPBOOTSTRAPANGULARXML
 

SQL GROUP BY 语句

Aggregate 函数常常需要添加 GROUP BY 语句。


GROUP BY 语句

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" 表的数据:

OrderIDCustomerIDEmployeeIDOrderDateShipperID
102489051996-07-043
102498161996-07-051
102503441996-07-082

选自 "Shippers" 表的数据:

ShipperIDShipperNamePhone
1Speedy Express(503) 555-9831
2United Package(503) 555-3199
3Federal Shipping(503) 555-9931

选自 "Employees" 表的数据:

EmployeeIDLastNameFirstNameBirthDatePhotoNotes
1DavolioNancy1968-12-08EmpID1.picEducation includes a BA....
2FullerAndrew1952-02-19EmpID2.picAndrew received his BTS....
3LeverlingJanet1963-08-30EmpID3.picJanet 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;
为什么有广告?:广告收入是作者继续投入更多业余时间的动力,也可以补贴服务器等的花费,本站也不会阻止屏蔽广告插件,请大家理解!