在两个表之间使用AVG()函数

时间:2010-10-04 22:03:09

标签: sql oracle aggregate-functions

我有两张桌子,我需要确定为任何职位提供最高平均工资的公司。我的表格如下:

employer
eID (primary key), eName, location

position
eID (primary key), pName (primary key), salary)

我写的代码确定所有高于1的平均工资,但我需要找到所有平均工资最高的

到目前为止,这是我的代码:

SQL> select eName
  2  from Employer E inner join position P on E.eID = P.eID
  3  where salary > (select avg(salary) from position);

这会输出高于最低平均值的所有工资,但我只需要最高的平均值。我尝试过使用avg(薪水)> (从位置选择avg(薪水))但我收到了不允许组功能的错误。

非常感谢任何帮助或建议!

2 个答案:

答案 0 :(得分:5)

使用:

SELECT x.eid, 
       x.ename, 
       x.avg_salary 
 FROM (SELECT e.eid,
              e.ename,
              AVG(p.salary) AS avg_salary,
              ROWNUM
         FROM EMPLOYER e
         JOIN POSTITION p ON p.eid = e.eid
     GROUP BY e.eid, e.ename
     ORDER BY avg_salary) x
 WHERE x.rownum = 1

Oracle 9i +:

SELECT x.eid, 
       x.ename, 
       x.avg_salary 
 FROM (SELECT e.eid,
              e.ename,
              AVG(p.salary) AS avg_salary,
              ROW_NUMBER() OVER(PARTITION BY e.eid
                                    ORDER BY AVG(p.salary) DESC) AS rank
         FROM EMPLOYER e
         JOIN POSTITION p ON p.eid = e.eid
     GROUP BY e.eid, e.ename) x
 WHERE x.rank = 1

以前,因为问题被标记为“mysql”:

  SELECT e.eid,
         e.ename,
         AVG(p.salary) AS avg_salary
    FROM EMPLOYER e
    JOIN POSTITION p ON p.eid = e.eid
GROUP BY e.eid, e.ename
ORDER BY avg_salary
   LIMIT 1

答案 1 :(得分:0)

select a.eid,
       a.ename,
       b.avg_salary
FROM EMPLOYER a
JOIN POSTITION b ON a.eid = b.eid
WHERE b.avg_salary =(SELECT max(x.avg_salary)
                      FROM (SELECT e.eid,
                                   e.ename,
                                   AVG(p.salary) AS avg_salary,
                            FROM EMPLOYER e
                            JOIN POSTITION p ON p.eid = e.eid
                            GROUP BY e.eid, e.ename) x
                    ) y