SQL HAVING

❮ 前章へ 次章へ ❯

HAVING Clause

HAVING clause was added to SQL because the WHERE keyword could not be used with aggregate functions.

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" テーブルからの抜粋です:

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

および "Employees" テーブルからの抜粋です:

EmployeeID LastName FirstName BirthDate Photo Notes
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 HAVING の例

Now we want to find  if any of the employees has registered more than 10 orders.

次の 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;

Try it Yourself ❯

Now we want to find if the employees "Davolio" or "Fuller" have registered more than 25 orders.

We add an ordinary WHERE clause to the SQL statement:

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;

Try it Yourself ❯

❮ 前章へ 次章へ ❯