SQL Server (Transact-SQL) HAVING 关键字用于指定聚合函数的条件。请注意,SQL Server (Transact-SQL) WHERE 关键字不能用于通过聚合函数指定条件。
语法
在 SQL Server (Transact-SQL) 中使用 HAVING 关键字的语法如下:
SELECT column_name(s)
FROM table_name
WHERE condition(s)
GROUP BY column_name(s)
HAVING condition(s)
ORDER BY column_name(s);
请注意,HAVING 子句必须遵循查询中的 GROUP BY 子句,如果使用,还必须位于 ORDER BY 子句之前。
示例:
考虑一个包含名为 Employee 和 Bonus_Paid表的数据库 包含以下记录:
表 1:Employee 表
EmpID | Name | City | Age | Salary |
---|---|---|---|---|
1 | John | London | 25 | 3000 |
2 | Marry | London | 24 | 2750 |
3 | Jo | London | 27 | 2800 |
4 | Kim | Amsterdam | 30 | 3100 |
5 | Ramesh | New Delhi | 28 | 3000 |
6 | Huang | Amsterdam | 28 | 2800 |
表 2:Bonus_Paid 表
EmpID | Bonus |
---|---|
1 | 500 |
2 | 400 |
3 | 450 |
4 | 550 |
5 | 400 |
6 | 600 |
获取包含员工人数的列表 (来自每个城市的员工表),并且仅包括拥有超过一名员工的城市,查询如下:
SELECT COUNT(EmpID) AS Number_of_Employee, City
FROM Employee
GROUP BY City
HAVING COUNT(EmpID) > 1;
这将产生如下所示的结果:
Number_of_Employee | City |
---|---|
2 | Amsterdam |
3 | London |
要根据员工数量按降序排列上述表格,查询将是:
SELECT COUNT(EmpID), City
FROM Employee
GROUP BY City
HAVING COUNT(EmpID) > 1
ORDER BY COUNT(EmpID) DESC;
查询结果将是:
Number_of_Employee | City |
---|---|
3 | London |
2 | Amsterdam |
在 JOIN 中使用 HAVING 关键字:要获取包含每个城市向员工支付的奖金的列表,并且仅包含拥有超过一名员工的城市,查询如下所示:
SELECT A.City, SUM(B.Bonus) AS BonusAmount
FROM Employee AS A
INNER JOIN Bonus_Paid AS B
ON A.EmpID = B.EmpID
GROUP BY City
HAVING COUNT(A.EmpID) > 1;
以下代码的结果将是:
City | BonusAmount |
---|---|
Amsterdam | 1150 |
London | 1350 |