Aggregate 函数常常需要添加 GROUP BY 语句。
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 GROUP BY示例
下面的 SQL 语句从 “Customers” 表中列出了每个国家/地区的客户数量:
SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country;
下面的 SQL 语句从 “Customers” 表中列出每个国家的客户数量,从高到低排序:
SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country
ORDER BY COUNT(CustomerID) DESC;
GROUP BY使用JOIN示例
下面的 SQL 语句从 “Orders” 和”Shippers”表中列出了每个发货人发送的订单数量:
SELECT Shippers.ShipperName, COUNT(Orders.OrderID) AS NumberOfOrders FROM Orders
LEFT JOIN Shippers ON Orders.ShipperID = Shippers.ShipperID
GROUP BY ShipperName;