使用HAVING命令代替WHERE和聚集函數(shù)。
以下SQL列出了每個(gè)國(guó)家/地區(qū)的客戶數(shù)量。但僅查詢擁有5個(gè)以上客戶的國(guó)家/地區(qū):
SELECT COUNT(CustomerID), Country FROM Customers GROUP BY Country HAVING COUNT(CustomerID) > 5;
以下SQL列出了每個(gè)國(guó)家/地區(qū)的客戶數(shù)量,從高到低排序(僅包括擁有5個(gè)以上客戶的國(guó)家/地區(qū)):
SELECT COUNT(CustomerID), Country FROM Customers GROUP BY Country HAVING COUNT(CustomerID) > 5 ORDER BY COUNT(CustomerID) DESC;