在嵌套聚合函数中,使用group by子句ex max(avg (salary ))
计算每个部门的第一个工资,假设分组由dept完成,然后选择max。现在我的理解是多个聚合函数如何工作
select max(dept), max(avg(salary))
from employee
group by dept;
这样的查询将如何运作?哪个聚合函数首先执行?任何人都可以帮助我,我是SQL新手。
答案 0 :(得分:2)
假设你有这张表:
create table employee (dept number(4), salary number(12));
insert into employee values (10, 1000);
insert into employee values (10, 5000);
insert into employee values (20, 2500);
insert into employee values (20, 3500);
insert into employee values (30, 2000);
部门的平均工资是:
select dept, avg(salary) avs from employee group by dept order by dept;
DEPT AVS
----- ----------
10 3000
20 3000
30 2000
您的查询显示department_id(30)的最大值和每个部门的平均工资的最大值。这些值无关。 换句话说,您的SQL显示以前输出的最大值。
select max(dept), max(avg(salary)) from employee group by dept;
DEPT AVS
----- ----------
30 3000
如果您想显示平均工资最高的部门,您可以选择多种方式 如果有多个这样的部门,一切都取决于你想做什么,就像在我的例子中,两个(10和20)具有相同,最高的平均值:
-- use HAVING clause with subquery (old school):
select dept, avg(salary) avs
from employee group by dept
having avg(salary) = (select max(avg(salary)) from employee group by dept)
order by dept;
-- use analytic MAX() function:
select dept, avs
from (
select dept, avg(salary) avs, max(avg(salary)) over () max_avs
from employee group by dept)
where avs = max_avs order by dept;
-- use analytic DENSE_RANK():
select dept, avs
from (
select dense_rank() over (order by avg(salary) desc) rnk, dept, avg(salary) avs
from employee group by dept)
where rnk = 1 order by dept;
-- if you want ONLY ONE ROW use MIN(...) or MAX(...) KEEP (DENSE_RANK...)
-- this returns department with lower ID:
select min(dept) keep (dense_rank last order by avg(salary)) dept,
min(avg(salary)) keep (dense_rank first order by avg(salary) desc) avs
from employee group by dept;
-- this returns department with higher ID:
select max(dept) keep (dense_rank last order by avg(salary)) dept,
max(avg(salary)) keep (dense_rank first order by avg(salary) desc) avs
from employee group by dept;