最新的Web開發教程
 

SQL HAVING子句


HAVING子句

加入HAVING子句SQL,因為WHERE關鍵字無法與合計函數一起使用。

SQL語法HAVING

SELECT column_name, aggregate_function(column_name)
FROM table_name
WHERE column_name operator value
GROUP BY column_name
HAVING aggregate_function(column_name) operator value;

演示數據庫

在本教程中,我們將使用眾所周知的Northwind示例數據庫。

下面是從選擇"Orders"表:

訂單ID 客戶ID 員工ID 訂購日期 ShipperID
10248 90 5 1996-07-04 3
10249 81 6 1996-07-05 1
10250 34 4 1996-07-08 2

而從選擇"Employees"表:

員工ID 名字 生日 照片 筆記
1 Davolio Nancy 1968-12-08 EmpID1.pic Education includes a BA....
2 Fuller Andrew 1952-02-19 EmpID2.pic Andrew received his BTS....
3 Leverling Janet 1963-08-30 EmpID3.pic Janet has a BS degree....

SQL具有例

現在,我們要找出是否有任何員工已註冊的10多個訂單。

我們用下面的SQL語句:

SELECT Employees.LastName, COUNT(Orders.OrderID) AS NumberOfOrders FROM (Orders
INNER JOIN Employees
ON Orders.EmployeeID=Employees.EmployeeID)
GROUP BY LastName
HAVING COUNT(Orders.OrderID) > 10;

試一試»

現在,我們希望找到,如果員工"Davolio""Fuller"已登記超過25個訂單。

我們添加一個普通的WHERE子句的SQL語句:

SELECT Employees.LastName, COUNT(Orders.OrderID) AS NumberOfOrders FROM Orders
INNER JOIN Employees
ON Orders.EmployeeID=Employees.EmployeeID
WHERE LastName='Davolio' OR LastName='Fuller'
GROUP BY LastName
HAVING COUNT(Orders.OrderID) > 25;

試一試»