表创建:
员工表:
DROP TABLE IF EXISTS `employee`;
CREATE TABLE `employee` (
`emp_id` int(11) NOT NULL AUTO_INCREMENT,
`dept_id` int(11) DEFAULT NULL,
`emp_wage` int(11) DEFAULT NULL,
PRIMARY KEY (`emp_id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
员工表数据:
insert into `employee`(`emp_id`,`dept_id`,`emp_wage`) values (1,1,10000),(2,2,20000),(3,4,5000),(4,4,3000),(5,3,7500);
部门表:
DROP TABLE IF EXISTS `department`;
CREATE TABLE `department` (
`dept_id` int(11) NOT NULL AUTO_INCREMENT,
`dept_name` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
PRIMARY KEY (`dept_id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
部门表数据:
insert into `department`(`dept_id`,`dept_name`) values (1,'信息部'),(2,'技术部'),(3,'外交部'),(4,'人事');
-----------------------------------
1) 求各部门的平均工资
select dept_name '部门名称',avg(emp_wage) "平均工资" from employee e left join department d on e.dept_id = d.dept_id GROUP BY emp_wage
2) 列出工资大于5000的员工所属部门名称、员工id和员工工资
select d.dept_name '部门名称',e.emp_id '员工id',
e.emp_wage'员工工资' from employee e left join department d on
e.dept_id=d.dept_id where e.emp_wage>5000
group by d.dept_name,e.dept_id ,e.emp_id,e.emp_wage