断点

每天进步一点点!
posts - 174, comments - 56, trackbacks - 0, articles - 21

SQL组合查询例子

Posted on 2010-07-06 23:25 断点 阅读(527) 评论(0)  编辑  收藏 所属分类: Oracle DBA

select e1.ename,e2.ename from emp e1 join emp e2 on (e1.mgr=e2.empno); --自连接,从e2中取出e1的经理人。
select ename,dname from emp e left join dept d on (e.deptno=d.deptno);   --左外连接
select ename,dname from emp e right outer join dept d on (e.deptno=d.deptno);   --右外连接
select ename,dname from emp e full join dept d on (e.deptno=d.deptno);    --全连接


--求部门中哪些人的薪水最高
select ename,sal from emp
join (select max(sal) max_sal,deptno from emp group by deptno) t
on (emp.sal = t.max_sal and emp.deptno = t.deptno);

--求部门平均薪水的等级
select deptno,avg_sal,grade from
(select deptno,avg(sal) avg_sal from emp group by deptno) t
join salgrade s on (t.avg_sal between s.losal and s.hisal);


--求部门平均的薪水等级
select avg(grade) from
(select deptno,ename,grade from emp join salgrade s on (emp.sal between s.losal and s.hisal )) t
group by deptno;

--雇员中有哪些人是经理人
select ename from emp where empno in (select distinct mgr from emp);


--不准用组函数,求薪水的最高值。采用的是自连接。
select distinct sal from emp where sal not in
(select distinct e1.sal from emp e1 join emp e2 on (e1.sal < e2.sal));


--求平均薪水最高的部门的部门编号。嵌套的组函数。
select deptno,avg_sal from
(select avg(sal) avg_sal,deptno from emp group by deptno)
where avg_sal =
(select max(avg(sal)),deptno from emp group by deptno;

 

--求平均薪水的等级最低的部门的部门名称。
select dname,t1.deptno,grade,avg_sal from
  (
   select deptno,grade,avg_sal from
     (select deptno,avg(sal) avg_sal from emp group by deptno) t
     join salgrade s on (t.avg_sal between s.losal and s.hisal)
  )
   t1
   join dept on (t1.deptno = dept.deptno)
)
where t1.grade =
(
 select min(grade) from
     (select deptno,grade,avg_sal from
  (select deptno,grade,avg(sal) avg_sal from emp group by deptno) t
   join salgrade s on (t.avg_sal between s.losal and s.hisal)
     )
)


--求平均薪水的等级最低的部门的部门名称。采用视图。
conn sys/sys as sysdba;
grant create table,create view to scott;

create view v$_dept_avg_sal_info as
select deptno,grade,avg_sal from
  (select deptno,grade,avg(sal) avg_sal from emp group by deptno) t
   join salgrade s on (t.avg_sal between s.losal and s.hisal);

select dname,t1.deptno,grade,avg_sal from
   v$_dept_avg_sal_info t1
   join dept on (t1.deptno = dept.deptno)
)
where t1.grade =
(
 select min(grade) from  v$_dept_avg_sal_info
)

-- 比普通员工的最高薪水还要高的经理人名称。
select ename from emp
where empno in (select distinct mgr from emp where mgr is not null)
and sal >
(
  select max(sal) from emp where empno not in
  (select distinct mgr from emp where mgr is not null)
)

 


只有注册用户登录后才能发表评论。


网站导航: