SQL GROUP BY 語句

2022-05-20 16:48 更新

SQL GROUP BY 語句


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

 GROUP BY語句通常與集合函數(shù)(COUNT,MAX,MIN,SUM,AVG)一起使用,以按一個(gè)或多個(gè)列對(duì)結(jié)果集進(jìn)行分組。


GROUP BY 語句


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

SQL GROUP BY 語法

SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
ORDER BY column_name(s);

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


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

 下面是選自 "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 GROUP BY示例


 以下SQL語句列出了每個(gè)國家/地區(qū)的客戶數(shù)量:

SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country;

 以下SQL語句列出每個(gè)國家的客戶數(shù)量,從高到低排序:

SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country
ORDER BY COUNT(CustomerID) DESC;

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


 以下是羅斯文示例數(shù)據(jù)庫中“訂單”表的一個(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

GROUP BY使用JOIN示例


 以下SQL語句列出了每個(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;
以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)