W3Cschool
恭喜您成為首批注冊(cè)用戶
獲得88經(jīng)驗(yàn)值獎(jiǎng)勵(lì)
Aggregate 函數(shù)常常需要添加 GROUP BY 語(yǔ)句。
GROUP BY語(yǔ)句通常與集合函數(shù)(COUNT,MAX,MIN,SUM,AVG)一起使用,以按一個(gè)或多個(gè)列對(duì)結(jié)果集進(jìn)行分組。
GROUP BY 語(yǔ)句用于結(jié)合 Aggregate 函數(shù),根據(jù)一個(gè)或多個(gè)列對(duì)結(jié)果集進(jìn)行分組。
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
ORDER BY column_name(s);
在本教程中,我們將使用眾所周知的 Northwind 樣本數(shù)據(jù)庫(kù)。
下面是選自 "Customers"表的數(shù)據(jù):
CustomerID | CustomerName | ContactName | Address | City | PostalCode | Country |
---|---|---|---|---|---|---|
1
|
Alfreds Futterkiste | Maria Anders | Obere Str. 57 | Berlin | 12209 | Germany |
2 | Ana Trujillo Emparedados y helados | Ana Trujillo | Avda. de la Constitución 2222 | México D.F. | 05021 | Mexico |
3 | Antonio Moreno Taquería | Antonio Moreno | Mataderos 2312 | México D.F. | 05023 | Mexico |
4
|
Around the Horn | Thomas Hardy | 120 Hanover Sq. | London | WA1 1DP | UK |
5 | Berglunds snabbk?p | Christina Berglund | Berguvsv?gen 8 | Lule? | S-958 22 | Sweden |
以下SQL語(yǔ)句列出了每個(gè)國(guó)家/地區(qū)的客戶數(shù)量:
SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country;
以下SQL語(yǔ)句列出每個(gè)國(guó)家的客戶數(shù)量,從高到低排序:
SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country
ORDER BY COUNT(CustomerID) DESC;
以下是羅斯文示例數(shù)據(jù)庫(kù)中“訂單”表的一個(gè)選擇:
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”表中選擇:
ShipperID | ShipperName |
---|---|
1 | Speedy Express |
2 | United Package |
3 | Federal Shipping |
以下SQL語(yǔ)句列出了每個(gè)發(fā)貨人發(fā)送的訂單數(shù)量:
SELECT Shippers.ShipperName, COUNT(Orders.OrderID) AS NumberOfOrders FROM Orders
LEFT JOIN Shippers ON Orders.ShipperID = Shippers.ShipperID
GROUP BY ShipperName;
Copyright©2021 w3cschool編程獅|閩ICP備15016281號(hào)-3|閩公網(wǎng)安備35020302033924號(hào)
違法和不良信息舉報(bào)電話:173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號(hào)
聯(lián)系方式:
更多建議: