根据两个不同的表获取MAX元素

时间:2014-10-25 16:56:33

标签: sql oracle

我在Oracle DB上遇到SQL查询问题。我有以下表格:

DEPARTMENT(`ID` NUMBER(11), `NAME` VARCHAR(25))    
EMPLOYEE(`ID` INT(11), `LASTNAME` VARCHAR(25), `DEP_ID` INT(11));
SALARIES(`ID` INT(11), `EMPLOYEE_ID` INT(11), `SALARY` INT(11));

现在,我希望获得最高工资平均值的贬低名称。部门与工资没有直接关系,所以我可能也需要使用员工表。

我创建了一个查询:

SELECT NAME, (SELECT SUM(SALARIES.SALARY) FROM SALARIES JOIN EMPLOYEE ON EMPLOYEE.EMPLOYEE_ID = EMPLOYEE.ID WHERE EMPLOYEE.DEP_ID = DEPARTMENT.ID GROUP BY EMPLOYEE.ID) AS AVG_OF_SUM FROM DEPARTMENT;

返回部门名称和平均值的列表。但是现在我只需要为最高的averange行获得一个部门名称。

我的查询确实可以吗?还是可以改进?我怎样才能获得一条记录?

感谢您的帮助。

此致 d

3 个答案:

答案 0 :(得分:0)

使用ANALYTIC函数SUM...OVER

在子查询中,应用分析函数,然后仅选择您想要的那些行。

例如,

SELECT DISTINCT DEPT, SUM(SAL) OVER (PARTITION BY DEPT ORDER_BY DEPT) SUM_SAL FROM EMPLOYEE ORDER_BY DEPT;

答案 1 :(得分:0)

SELECT NAME, (SELECT MAX(SUM(SALARIES.SALARY))
              FROM SALARIES
              JOIN EMPLOYEE ON EMPLOYEE.EMPLOYEE_ID = EMPLOYEE.ID )
              WHERE EMPLOYEE.DEP_ID = DEPARTMENT.ID 
              GROUP BY EMPLOYEE.ID) AS AVG_OF_SUM FROM DEPARTMENT;

答案 2 :(得分:0)

SELECT NAME, avg_sal FROM
    (SELECT d.NAME, avg(s.SALARY) avg_sal
      FROM SALARIES s
      JOIN EMPLOYEE e ON s.EMPLOYEE_ID = e.ID
      JOIN DEPARTMENT d ON e.DEP_ID = d.ID
    GROUP BY d.NAME
    ORDER BY 2 DESC)
WHERE rownum = 1;

(此查询显示平均薪资最高的部门。如果您需要总和替换AVG - > SUM)