作为程序员一定要保持良好的睡眠,才能好编程

部门表 department 部门编号 dept_id 部门名称 汇总表

发布时间:2018-11-05

有两张表

部门表  department  部门编号 dept_id 部门名称 dept_mement

create table department(

dept_id tinyint auto_increment primary key,

dept_mement varchar(30)

)engine=InnoDB default charset utf8;

insert into department(dept_id,dept_mement)values(1,"财务部"),(2,"网络部"),(3,"业务部");

员工表 employee 员工编号 emp_id  姓名 emp_name 部门编号 emp_deptId 工资 emp_wage

create table employee(

emp_id int auto_increment primary key,

emp_name varchar(255) not null,

emp_deptId tinyint default 0,

emp_wage decimal(10,2) default 0

)engine=InnoDB default charset utf8;

insert into employee(emp_name,emp_deptId,emp_wage)values("张三",1,4000),("李四",1,8600),("lily",2,13000),("lucy",2,7000),("jim",2,9000),("苹果",3,5000),("梨",3,8000),("香蕉",3,5800),("芒果",3,14000),("橘子",3,6800);

请根据要求写出下列sql语句

1、列出工资大于10000的员工所属的部门编号

select distinct(dept_id) from employee left join department on department.dept_id=employee.emp_deptId where employee.emp_wage>10000;

select dept_id from department where dept_id in(select emp_deptId from employee where emp_wage>10000);

2、列出员工表中的部门名称(左连接)

    select e.*,d.dept_mement from employee as e left join department as d on d.dept_id=e.emp_deptId;

3、列出员工少于3人的部门编号

select count(*) as n, emp_deptId as dept_id from employee GROUP BY emp_deptId HAVING n<3;

select emp_deptId as dept_id from employee GROUP BY emp_deptId HAVING count(*)<3;

4、列出工资最高的员工姓名

select * from employee order by emp_wage desc limit 1;

5、求各部门的平均工资,并保留了两位小数  

select truncate(AVG(emp_wage),2),emp_deptId from employee GROUP BY emp_deptId;

6、求各部门的员工工资总额

select sum(emp_wage),emp_deptId from employee group by emp_deptId;

select sum(emp_wage),count(*) as shuliang ,emp_deptId from employee group by emp_deptId;

显示总额和 总人数 以及部门名称

7、求各部门中的最大工资和最小工资,并且它的最小值小于5000 最大值大于8000

select min(emp_wage) as smallp,max(emp_wage) as maxp from employee group by emp_deptId HAVING smallp<5000 and maxp>8000;

第二大题 加入现在库中有个一和员工表结构相同的空表 employee2 请用一条sql语句 将员工表中所有的数据插入到employee2中。

例如两张表的结构:

create table employee(
emp_id int auto_increment primary key,
emp_name varchar(255) not null,
emp_deptId tinyint default 0,
emp_wage decimal(10,2) default 0
)engine=InnoDB default charset utf8;

create table employee2(
emp_id int auto_increment primary key,
emp_name varchar(255) not null,
emp_deptId tinyint default 0,
emp_wage decimal(10,2) default 0
)engine=InnoDB default charset utf8;


insert into employee2(emp_id,emp_name,emp_deptId,emp_wage) select emp_id,emp_name,emp_deptId,emp_wage from employee;