SQL server内连接查询

内连接

select top* 
from A
join B
on...
join C
on...
where...
group by...
having...
order by...

1.//在scott表中查询员工名字中不包含A的所有员工,前三名员工的姓名,工资,工资等级,部门名字

select top 3 "E".ename,"E".sal,"S".grade,"D".dname 
from emp "E" 
join dept "D" on "E".deptno="D".deptno 
join salgrade "S" on "E".sal>=losal and "E".sal<=hisal      //或on "E".sal  between "S".losal and "S".hisal
where "E".ename not like '%A%'    //注意这句话要放在最后
order by "E".sal desc    //注意这句话要放在最后

2.//在scott表中查找每个部门编号,部门名称,该部门所有员工的平均工资,平均工资的等级
select "T".deptno,"T".avg_sal "部门员工平均工资","S".grade "工资等级","D".dname "部门名称"
from(
select deptno,avg(sal)as "avg_sal"    //将查询结果当作临时表
from emp 
group by deptno
) "T"
join salgrade "S" 
on "T".avg_sal  between "S".losal and "S".hisal
join dept "D"
on "T".deptno="D".deptno

等价于以下写法(join 前后 两个部分互换)

select "T".deptno,"T".avg_sal "部门员工平均工资","S".grade "工资等级","D".dname "部门名称"
from salgrade "S"
join (
select deptno,avg(sal)as "avg_sal"    
from emp 
group by deptno
) "T"
         /将查询结果当作临时表
on "T".avg_sal  between "S".losal and "S".hisal
join dept "D"

on "T".deptno="D".deptno

3.// 查询平均薪水最高的部门名称,编号,工资
select "T".avg_sal, "T".deptno,"D".dname 
from
(select top 1 avg(sal)"avg_sal",deptno from emp group by deptno order by deptno) "T" 将查询结果当作临时表

join dept "D" on "T".deptno="D".deptno

4.//排除最低工资的员工后,查询剩下员工中工资最低的3位员工的姓名,工资,部门编号,部门名称,工资等级。
select top 3 "T".ename "姓名","T".sal "工资","T".deptno "部门编号","D".dname "部门名称","S".grade "工资等级"
from (select * from emp where sal>(select min(sal) from emp) ) "T"      /将查询结果当作临时表
join dept "D"on("T".deptno="D".deptno) 
join salgrade "S"on("T".sal between "S".losal and "S".hisal )
        order by "T".sal    ///注意这句话要放在最后


5

select * from emp 
join dept

on emp.deptno=dept.deptno and emp.sal>2000    //on中即可以写连接条件与可以写过滤条件

等价于:

select * from emp     //将查询对象互换
join dept

on emp.deptno=dept.deptno and emp.sal>2000    //on中即可以写连接条件与可以写过滤条件


等价于:

select * from emp 
join dept
on emp.deptno=dept.deptno

where emp.sal>2000    //where连接条件

等价于:

        select * from emp 
join dept
on emp.sal>2000
where emp.deptno=dept.deptno    //将两条件互换

6.查询基本模式

    select top* 
from A
join B
on...
join C
on...
where...
group by...
having...
order by...

   例:把工资大于1500的所有员工按部门分组,把部门平均工资大于2000的最高前2个的部门的编号,部门的名称,部门平均工资 的等级输出

select "T".*,"D".dname, "S".grade 
from dept "D" 
join(
select top 2 "E".deptno,avg("E".sal) "avg_sal"
from emp "E"
join dept "D" on "E".deptno="D".deptno 
join salgrade "S" on "E".sal between "S".losal and "S".hisal     //这两句不要,也两样可行。

where "E".sal>1500 
group by "E".deptno 
having avg("E".sal)>2000
order by "avg_sal" desc
)"T"    //当作临时表
on "T".deptno="D".deptno
join salgrade "S"
on "T".avg_sal 
between "S".losal and "S".hisal

你可能感兴趣的:(数据库)