平均sal然后按降序排序

时间:2011-09-10 17:20:40

标签: sql oracle aggregate-functions

我想列出所有超过平均工资的员工。我对这一点感到很失落。我需要将所有薪水加起来然后平均出来,只显示那些超过平均水平的薪水。我需要很多这方面的帮助。

我的查询无效

 SQL> select empno, ename, job, hiredate, sal, deptno from emp where sal avg(sal);
 select empno, ename, job, hiredate, sal, deptno from emp where sal avg(sal)
                                                               *
 ERROR at line 1:
 ORA-00920: invalid relational operator
 SQL>

SQL> select empno, ename, job, hiredate, sal, deptno from emp;

 EMPNO ENAME      JOB       HIREDATE         SAL     DEPTNO
 ---------- ---------- --------- --------- ---------- ----------
  7839 KING       PRESIDENT 17-NOV-81       5000         10
  7698 BLAKE      MANAGER   01-MAY-81       2850         30
  7782 CLARK      MANAGER   09-JUN-81       2450         10
  7566 JONES      MANAGER   02-APR-81       2975         20
  7654 MARTIN     SALESMAN  28-SEP-81       1250         30
  7499 ALLEN      SALESMAN  20-FEB-81       1600         30
  7844 TURNER     SALESMAN  08-SEP-81       1500         30
  7900 JAMES      CLERK     03-DEC-81        950         30
  7521 WARD       SALESMAN  22-FEB-81       1250         30
  7902 FORD       ANALYST   03-DEC-81       3000         20
  7369 SMITH      CLERK     17-DEC-80        800         20

 EMPNO ENAME      JOB       HIREDATE         SAL     DEPTNO
 ---------- ---------- --------- --------- ---------- ----------
  7788 SCOTT      ANALYST   09-DEC-82       3000         20
  7876 ADAMS      CLERK     12-JAN-83       1100         20
  7934 MILLER     CLERK     23-JAN-82       1300         10

 14 rows selected.

2 个答案:

答案 0 :(得分:4)

您收到无效的关系运算符错误,因为您忽略了less than 登录您的查询。请学习阅读the documentation.

除此之外,您还需要编写一个子查询来计算平均工资。所以你的查询应该是这样的:

select empno, ename, job, hiredate, sal, deptno 
from emp 
where sal > (select  avg(sal) from emp)
order by sal desc;

答案 1 :(得分:4)

Oracle不支持windowed functions吗?我不确定您是否可以直接在WHERE子句中使用窗口函数,但至少可以从使用它的查询派生一个表,然后在条件中引用相应的列:

SELECT
  empno, ename, job, hiredate, sal, deptno
FROM (
  SELECT
    empno, ename, job, hiredate, sal, deptno
    AVG(sal) OVER () AS avgsal
  FROM emp
) s
WHERE sal > avgsal