自强学堂
自强学堂:学习、分享、让你更强!
SQL 教程HTMLCSSJAVASCRIPTJQUERYSQLPHPBOOTSTRAPANGULARXML
 

SQL HAVING 子句

HAVING 子句

在 SQL 中增加 HAVING 子句原因是,WHERE 关键字无法与 Aggregate 函数一起使用。

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" 表的数据:

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

选自 "Employees" 表的数据:

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 实例

现在我们想要查找订单总数少于 2000 的客户。

我们使用下面的 SQL 语句:

下面的 SQL 语句查找注册超过 10 个订单的员工:

实例

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 个订单。

我们在 SQL 语句中增加一个普通的 WHERE 子句:

实例

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;
为什么有广告?:广告收入是作者继续投入更多业余时间的动力,也可以补贴服务器等的花费,本站也不会阻止屏蔽广告插件,请大家理解!