题目是从emp中查询出工资大于所在部门平均工资的员工信息,按照视频上的说法需要这样写
select a2.ename, a2.sal, a2.deptno, a1.mysal from emp a2, (select deptno , avg(sal) mysal from emp group by deptno) a1 where a2.deptno = a1.deptno and a2.sal > a1.mysal;
要给子表查询起个别名,可是我在plsql中运行下面的语句结果同样正确:
select * from emp where sal > (select avg(sal) from emp where deptno = deptno);
但是视频中说不能这样写,不明白上面的写法是不合规范还是在旧版本的Oracle中会报错?我用的是Oracle11g
select a2.ename, a2.sal, a2.deptno, a1.mysal from emp a2, (select deptno , avg(sal) mysal from emp group by deptno) a1 where a2.deptno = a1.deptno and a2.sal > a1.mysal;
要给子表查询起个别名,可是我在plsql中运行下面的语句结果同样正确:
select * from emp where sal > (select avg(sal) from emp where deptno = deptno);
但是视频中说不能这样写,不明白上面的写法是不合规范还是在旧版本的Oracle中会报错?我用的是Oracle11g
第1条SQL执行的结果:
ENAME SAL DEPTNO MYSAL
1 KING 5000.00 10 2916.66666666667
2 FORD 3000.00 20 2175
3 SCOTT 3000.00 20 2175
4 JONES 2975.00 20 2175
5 ALLEN 1600.00 30 1566.66666666667
6 BLAKE 2850.00 30 1566.66666666667
第2条SQL执行的结果:
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
1 7782 CLARK MANAGER 7839 1981-6-9 2450.00 10
2 7839 KING PRESIDENT 1981-11-17 5000.00 10
3 7566 JONES MANAGER 7839 1981-4-2 2975.00 20
4 7902 FORD ANALYST 7566 1981-12-3 3000.00 20
5 7788 SCOTT ANALYST 7566 1987-4-19 3000.00 20
6 7698 BLAKE MANAGER 7839 1981-5-1 2850.00 30
兄弟看到差别了吗?
你第1条SQL是按部门平均,第2条SQL是全部的平均。
DEPTNO=10的平均工资2916.66666666667
第2条SQL中却查出
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
1 7782 CLARK MANAGER 7839 1981-6-9 2450.00 10
SAL=2450.00小于平均工资。
题干
是“工资大于所在部门”
不是“工资大于所有部门”
楼主看明白了吗?
以后要细心,不要看表面。
失之毫厘谬之千里。
你不写别名能够执行成功那是因为select avg(sal) from emp where deptno = deptno 和select avg(sal) from emp where 1=1 没有任何区别,只是求个平均值。所以就相当于select * from emp where sal > 某个值而已。
select * from emp a where sal > (select avg(sal) from emp where deptno =a.deptno
group by deptno);