1. Aggregate 函数常常需要添加 GROUP BY 语句
2. GROUP BY语句通常与集合函数(COUNT,MAX,MIN,SUM,AVG)一起使用,以按一个或多个列对结果集进行分组。
SQL GROUP BY 语法
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
ORDER BY column_name(s);
示例
需求 : SQL语句列出了每个国家/地区的客户数量
SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country;
需求 :SQL语句列出每个国家的客户数量,从高到低排序:
SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country
ORDER BY COUNT(CustomerID) DESC;
GROUP BY使用JOIN示例
需求:SQL语句列出了每个发货人发送的订单数量:
SELECT Shippers.ShipperName, COUNT(Orders.OrderID) AS NumberOfOrders FROM Orders
LEFT JOIN Shippers ON Orders.ShipperID = Shippers.ShipperID
GROUP BY ShipperName;