SQL HAVING 子句

2020-12-28 09:07 更新

SQL HAVING 子句


HAVING 子句

在 SQL 中增加 HAVING 子句原因是,WHERE 關(guān)鍵字無法與 Aggregate 函數(shù)一起使用。

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;


演示數(shù)據(jù)庫

在本教程中,我們將使用眾所周知的 Northwind 樣本數(shù)據(jù)庫。

下面是選自 "Orders" 表的數(shù)據(jù):

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" 表的數(shù)據(jù):

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 實(shí)例

現(xiàn)在我們想要查找訂單總數(shù)少于 2000 的客戶。

我們使用下面的 SQL 語句:

下面的 SQL 語句查找注冊(cè)超過 10 個(gè)訂單的員工:

實(shí)例

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;

現(xiàn)在我們想要查找員工 "Davolio" 或 "Fuller" 是否擁有超過 25 個(gè)訂單。

我們?cè)?SQL 語句中增加一個(gè)普通的 WHERE 子句:

實(shí)例

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;
以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)