2019-03-27多行查询,多列查询

-- today ------------------------------------------------------------------------

-- 多行子查询

-- in

-- 查询是经理的姓名,工资

select ename,sal

from emp

where empno  in (select mgr from emp)

-- 查询不是经理的姓名,工资

-- 注意:not in(不能为空)

select ename,sal

from emp

where empno not in (select mgr from emp where mgr is not null)

-- ANY : =any(和in意思相同)

-- 查询工资高于10部门任意一名员工

select *

from emp

where sal >any(select sal from emp where deptno = 10)

-- all 了解

-- 查询工资高于20部门所有员工

select *

from emp

where sal >all(select sal from emp where deptno = 20)

-- 注意:当子查询返回一条以上的记录时不可以用<,>,=,>=,<=,!=

-- 多列子查询

-- 9.查询员工工资为其部门最低工资的员工的编号和姓名及工资。

select ename,sal

from emp

where (deptno,sal)

in (select deptno,min(sal) from emp GROUP BY deptno )

-- 16. 显示每个部门的最高工资的员工

select ename,sal

from emp

where (deptno,sal)

in (select deptno,max(sal) from emp GROUP BY deptno )

select ename,sal

from emp e

join (select deptno,max(sal) maxsal from emp GROUP BY deptno ) d

on e.deptno = d.deptno

where sal = maxsal

-- 查询可以当表使用,查询到的数据可以理解为表的数据

-- 查询比自己部门平均工资高的员工姓名,工资,部门平均工资

select e.deptno,ename,sal,avgsal

from emp e

join (select deptno,AVG(sal) avgsal from emp GROUP BY deptno) d

on e.deptno = d.deptno

where sal > avgsal

-- 相关子查询

-- 查询每个部门工资最高的姓名工资

select empno,ename,sal,deptno

from emp

where (deptno,sal) in (select deptno,max(sal) from emp GROUP BY deptno )

select ename,sal

from emp e

join (select deptno,max(sal) maxsal from emp GROUP BY deptno ) d

on e.deptno = d.deptno

where sal = maxsal

--  相关

select empno,ename,sal,deptno

from emp e

where sal=(select max(sal) from emp where deptno= e.deptno)

-- 查询比自己部门平均工资高的员工姓名,工资,部门平均工资

select e.deptno,ename,sal,avgsal

from emp e

join (select deptno,AVG(sal) avgsal from emp GROUP BY deptno) d

on e.deptno = d.deptno

where sal > avgsal

-- 显示部门和人数

select dname,count(empno)

from emp

join dept

on dept.deptno = emp .deptno

GROUP BY dname

select dname, (select count(deptno) from emp  where deptno = e.deptno ) renshu

from dept e



3.列出001号成绩比002号成绩分数高的所有学生学号

  select s1.sno

  from SC s1

  group by s1.sno

  having (select scgrade from sc c where cno = 001 and s1.sno= c.sno ) > (select scgrade from sc c where cno = 002  and s1.sno= c.sno)



-- 5.删除学生 表中同名的学员,只保留SNO最大的记录

delete from  s

where sno not in (

      select maxsno from (  select MAX(sno) maxsno from  s group by sname  ) s

你可能感兴趣的:(2019-03-27多行查询,多列查询)