📅  最后修改于: 2020-11-15 03:49:36             🧑  作者: Mango
在Oracle GROUP BY子句中与SELECT语句一起使用可从多个记录中收集数据,并将结果按一个或多个列分组。
句法:
SELECT expression1, expression2, ... expression_n,
aggregate_function (aggregate_expression)
FROM tables
WHERE conditions
GROUP BY expression1, expression2, ... expression_n;
expression1,expression2,… expression_n:它指定未封装在聚合函数的表达式。这些表达式必须包含在GROUP BY子句中。
gregation_function:它指定聚合函数,即SUM,COUNT,MIN,MAX或AVG函数。
gregation_expression:指定聚合函数所基于的列或表达式。
表:它指定要从中检索记录的表。
条件:它指定要选择的记录必须满足的条件。
让我们来一张桌子“ 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;
输出量
上面的示例将显示每个项目的总销售额。
让我们来一张桌子“客户”
在这里,我们创建一个名为客户的表。该表没有任何主键。
客户表:
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;
输出:
让我们来一张桌子“员工”
员工表:
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;
输出:
在此示例中,我们使用上面给出的“员工”表。
执行此查询:
SELECT department,
MAX(salary) AS "Highest salary"
FROM employees
GROUP BY department;
输出: