当前位置:数据库 > Oracle >>

oracle基本语句学习之子查询

oracle基本语句学习之子查询
 
1 子查询
 
  ex:  查出 姓名, 其工资在平均工资之上
 
      
select  ename,sal from emp where sal > (select avg(sal) from emp) ;

 

 
 
 2 见表子查询
 
     查询每个部门中工资最高的人 .
 
     直观方法   
select ename,sal from emp  where  sal  in (select max(sal) from emp group by deptno) ;

 

 
                     这样的查询方式会出现一个错误, 假如 A部门最高薪水5000, 而A部门的p员工薪水3000, 却等于B部门的最高薪水, 那么员工也将显示出来;
 
 
    正确方法如下:
 
                       首先 , 可以发现 select max(sal) from emp group by deptno  能得到一张表 , 如下图所示
 
                      
 
 
 
                            那么 只要在emp中找到部门 和薪水都与此表一致的员工即可.
 
 
               语句如下: 
 
                            
  1 select ename ,sal from emp

                               2 join (select max(sal)max_sal, deptno  from emp  group by deptno) t   //连接表

                               3 on( emp.sal=t.max_sal and emp.deptno=t.deptno) ;  // 连接条件

 

 
               
 
                           
Oracle
MySQL
Access
SQLServer
DB2
Excel
SQLite
SYBASE
Postgres
如果你遇到数据库难题:
请访问www.zzzyk.com 试试
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,