📅  最后修改于: 2020-11-15 03:50:48             🧑  作者: Mango
在Oracle中,HAVING子句与GROUP BY子句一起使用以限制条件为TRUE时返回的行的组。
句法:
SELECT expression1, expression2, ... expression_n,
aggregate_function (aggregate_expression)
FROM tables
WHERE conditions
GROUP BY expression1, expression2, ... expression_n
HAVING having_condition;
expression1,expression2,… expression_n:它指定未封装在聚合函数的表达式。这些表达式必须包含在GROUP BY子句中。
gregation_function:它指定聚合函数,即SUM,COUNT,MIN,MAX或AVG函数。
gregation_expression:指定聚合函数所基于的列或表达式。
表:它指定要从中检索记录的表。
条件:它指定要选择的记录必须满足的条件。
hading_conditions:指定仅适用于汇总结果的条件,以限制返回的行的组。
让我们来一张桌子“ salesdepartment”
销售部门表:
CREATE TABLE "SALESDEPARTMENT"
( "ITEM" VARCHAR2(4000),
"SALE" NUMBER,
"BILLING_ADDRESS" VARCHAR2(4000)
)
/
执行此查询:
SELECT item, SUM(sale) AS "Total sales"
FROM salesdepartment
GROUP BY item
HAVING SUM(sale) < 1000;
输出:
让我们来一张桌子“客户”
客户表:
CREATE TABLE "CUSTOMERS"
( "NAME" VARCHAR2(4000),
"AGE" NUMBER,
"SALARY" NUMBER,
"STATE" VARCHAR2(4000)
)
/
执行此查询:
SELECT state, COUNT(*) AS "Number of customers"
FROM customers
WHERE salary > 10000
GROUP BY state
HAVING COUNT(*) >= 2;
输出:
让我们来个表格“员工”
员工表:
CREATE TABLE "EMPLOYEES"
( "EMP_ID" NUMBER,
"NAME" VARCHAR2(4000),
"AGE" NUMBER,
"DEPARTMENT" VARCHAR2(4000),
"SALARY" NUMBER
)
/
执行此查询:
SELECT department,
MIN(salary) AS "Lowest salary"
FROM employees
GROUP BY department
HAVING MIN(salary) < 15000;
输出量
执行此查询:
SELECT department,
MAX(salary) AS "Highest salary"
FROM employees
GROUP BY department
HAVING MAX(salary) > 30000;
输出: