我需要帮助。我有表Employees和table Departments。我需要得到最高薪水的部门。 我试试这个:
SELECT department_name,MAX(sum_salary) as sum_salary
FROM (SELECT department_name,SUM(salary) AS sum_salary
FROM EMPLOYEES,DEPARTMENTS
WHERE DEPARTMENTS.DEPARTMENT_ID = EMPLOYEES.DEPARTMENT_ID
GROUP BY DEPARTMENT_NAME)
GROUP BY DEPARTMENT_NAME;
但结果是部门列表,而不仅仅是一个值。
感谢您的帮助!
答案 0 :(得分:1)
select
min(max(department_name)) keep (dense_rank last order by sum(salary))
as department_name,
min(sum(salary)) keep (dense_rank last order by sum(salary))
as sum_salary
from EMPLOYEES join DEPARTMENTS using(department_id)
group by department_id
答案 1 :(得分:0)
如果在关系的情况下,你只想要一个,那么order by
和某种形式的获得一行是有效的。 ANSI标准方法是:
SELECT d.DEPARTMENT_NAME, SUM(e.salary) AS sum_salary
FROM EMPLOYEES e JOIN
DEPARTMENTS d
ON d.DEPARTMENT_ID = e.DEPARTMENT_ID
GROUP BY d.DEPARTMENT_NAME
ORDER BY SUM(e.salary) DESC
FETCH FIRST 1 ROW ONLY;
请注意使用正确的JOIN
语法和表别名。
编辑:
Oracle 12g支持上述语法。您可以在早期版本中执行以下操作:
SELECT t.*
FROM (SELECT d.DEPARTMENT_NAME, SUM(e.salary) AS sum_salary
FROM EMPLOYEES e JOIN
DEPARTMENTS d
ON d.DEPARTMENT_ID = e.DEPARTMENT_ID
GROUP BY d.DEPARTMENT_NAME
ORDER BY SUM(e.salary) DESC
) t
WHERE rownum = 1;
Here's一个SQL小提琴。
答案 2 :(得分:0)
等等 - 还有另一种方式:
WITH SUM_SAL AS (SELECT d.DEPARTMENT_NAME, SUM(e.SALARY) AS SUM_SALARY
FROM EMPLOYEES e
INNER JOIN DEPARTMENTS d
ON d.DEPARTMENT_ID = e.DEPARTMENT_ID
GROUP BY DEPARTMENT_NAME),
MAX_SAL AS (SELECT MAX(SUM_SALARY) AS MAX_SALARY
FROM SUM_SAL)
SELECT s.DEPARTMENT_NAME, m.MAX_SALARY
FROM SUM_SAL s
INNER JOIN MAX_SAL m
ON m.MAX_SALARY = s.SUM_SALARY;
祝你好运。