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;
试一试»