emp数据表建表语句:
create table emp(
empno int,
ename varchar(40),
job varchar(40),
mgr int,
hiredate varchar(40),
sal double,
comm int,
deptno int
);
插入数据准备:
insert into emp values (7349,'clerk','engineer',7510,'1980-04-07',9100,null,10);
insert into emp values (7359,'smith','IT',7540,'1991-05-07',7500,500,10);
insert into emp values (7369,'will','develpoer',7270,'1996-12-07',6000,300,10);
insert into emp values (7500,'ron','engineer',7489,'1995-06-015',8500,null,20);
insert into emp values (7510,'john','salesman',7648,'1989-08-04',7200,500,20);
insert into emp values (7520,'fox','manager',7718,'1987-09-07',6000,300,20);
insert into emp values (7600,'earth','clerk',7716,'1991-10-07',9500,3000,30);
insert into emp values (7610,'zack','IT',7634,'1992-06-05',8800,1500,30);
insert into emp values (7620,'steven','engineer',7951,'1993-07-07',7500,null,30);
1、分析:每个部门、每个工种的薪水和:
1、可以建立一个视图:
create view sal
as
select
deptno,job,sum(sal+ifnull(comm,0)) as sal
from emp group by deptno,job;
2、select * from sal; 视图中查询数据
两张表都是sal,一张表设为sal.a,另一张表设为sal.b;从结果集来看:这两张表是一样的
再插入一条数据后,再次进行SQL查询:
select
a.*
from sal a
where (
select count(*) from sal b
where a.deptno=b.deptno and a.sal < b.sal
) = 0;
如果我们要取出top2的话,该怎么修改SQL?
select
a.*
from sal a
where (
select count(*) from sal b
where a.deptno=b.deptno and a.sal < b.sal
) <= 1;
1、以部门升序,薪水降序
select
a.*
from sal a
where (
select count(*) from sal b
where a.deptno=b.deptno and a.sal < b.sal
) <= 1
order by a.deptno,a.sal desc;