2015. 6. 20. 23:16


http://www.w3schools.com/sql/sql_having.asp


The HAVING Clause

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

SQL HAVING Syntax

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;

Demo Database

In this tutorial we will use the well-known Northwind sample database.

Below is a selection from the "Orders" table:

OrderIDCustomerIDEmployeeIDOrderDateShipperID
102489051996-07-043
102498161996-07-051
102503441996-07-082

And a selection from the "Employees" table:

EmployeeIDLastNameFirstNameBirthDatePhotoNotes
1DavolioNancy1968-12-08EmpID1.picEducation includes a BA....
2FullerAndrew1952-02-19EmpID2.picAndrew received his BTS....
3LeverlingJanet1963-08-30EmpID3.picJanet has a BS degree....

SQL HAVING Example

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

We use the following SQL statement:

Example

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:

Example

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 »


'SQL' 카테고리의 다른 글

LCASE() Function  (0) 2015.06.20
The UCASE() Function  (0) 2015.06.20
GROUP BY Statement  (0) 2015.06.20
SUM() Function  (0) 2015.06.20
MIN() Function  (0) 2015.06.20
Posted by Name_null