我遇到了一个查询,我无法让它正常工作。
这就是我需要做的事情:
编写一个将返回最大和最小平均值的查询 按雇员表格按部门分组的工资。
这就是我所做的:
SELECT
(SELECT AVG(MIN(salary)) FROM employees GROUP BY department_id) As "Minimum Average salary",
(SELECT AVG(MAX(salary)) FROM employees GROUP BY department_id) As "Maximum Average Salary"
FROM EMPLOYEES
但它不断返回我超过1行的结果。我不能使用LIMIT 2,如果我用LIMIT查询,我会收到错误。
我也尝试过以下查询,但是我收到错误:缺少表达式。
SELECT
AVG(SELECT MIN(salary) FROM employees GROUP BY department_id)) As "Minimum Average salary",
AVG((SELECT MAX(salary) FROM employees GROUP BY department_id)) As "Maximum Average Salary"
FROM EMPLOYEES
答案 0 :(得分:4)
无需内联视图 - 这有效:
select
min(avg(salary)),
max(avg(salary))
from
employees
group by
dept_id;
答案 1 :(得分:1)
使用子查询检索所有平均工资。然后外部查询可以获取最小值和最大值:
select min(AvgSalary)
, max(AvgSalary)
from (
select avg(salary) as AvgSalary
from employees
group by
department_id
) SubQueryAlias
答案 2 :(得分:1)
首先,它很简单,为什么它返回的数量与EMPLOYEES表中的所有记录一样多;因为group by位于您的内部子查询中,而不会应用于您的主查询。实际上,对表中的每一行执行子查询,并且每行返回结果。 我认为这是您需要的正确查询:
SELECT AVG(min_salary) As "Minimum Average salary", AVG(max_salary) As "Maximum Average Salary"
FROM
(SELECT MIN(salary) As min_salary, MAX(salary) AS max_salary
FROM EMPLOYEES
GROUP BY department_id
)
答案 3 :(得分:0)
select MAX(salary),min(salary), avg(salary), department_id from employees group by department_id