SQL GROUP BY 語句

2019-10-26 16:28 更新

SQL GROUP BY 語句


Aggregate 函數(shù)常常需要添加 GROUP BY 語句。


GROUP BY 語句

GROUP BY 語句用于結(jié)合 Aggregate 函數(shù),根據(jù)一個(gè)或多個(gè)列對結(jié)果集進(jìn)行分組。

SQL GROUP BY 語法

SELECT column_name, aggregate_function(column_name)
FROM table_name
WHERE column_name operator value
GROUP BY column_name;


演示數(shù)據(jù)庫

在本教程中,我們將使用眾所周知的 Northwind 樣本數(shù)據(jù)庫。

下面是選自 "Orders" 表的數(shù)據(jù):

OrderID CustomerID EmployeeID OrderDate ShipperID
10248 90 5 1996-07-04 3
10249 81 6 1996-07-05 1
10250 34 4 1996-07-08 2

選自 "Shippers" 表的數(shù)據(jù):

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

選自 "Employees" 表的數(shù)據(jù):

EmployeeID LastName FirstName BirthDate Photo Notes
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 實(shí)例

現(xiàn)在我們想要查找每個(gè)送貨員配送的訂單數(shù)目。

下面的 SQL 語句按送貨員進(jìn)行訂單分類統(tǒng)計(jì):

實(shí)例

SELECT Shippers.ShipperName,COUNT(Orders.OrderID) AS NumberOfOrders FROM Orders
LEFT JOIN Shippers
ON Orders.ShipperID=Shippers.ShipperID
GROUP BY ShipperName;


GROUP BY 一個(gè)以上的列

我們也可以對一個(gè)以上的列應(yīng)用 GROUP BY 語句,如下所示:

實(shí)例

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;
以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號