题目
汇总各个部门当前员工的title类型的分配数目,
即结果给出部门编号dept_no、dept_name、
其部门下所有的员工的title以及该类型title对应的数目count,
结果按照dept_no升序排序,dept_no一样的再按title升序排序
解题思路:
1. 弄一个含有title的表
2. 联结 department 表
3. 分组
4. 排序
原数据
drop table if exists `departments` ; drop table if exists `dept_emp` ; drop table if exists titles ; CREATE TABLE `departments` ( `dept_no` char(4) NOT NULL, `dept_name` varchar(40) NOT NULL, PRIMARY KEY (`dept_no`)); CREATE TABLE `dept_emp` ( `emp_no` int(11) NOT NULL, `dept_no` char(4) NOT NULL, `from_date` date NOT NULL, `to_date` date NOT NULL, PRIMARY KEY (`emp_no`,`dept_no`)); CREATE TABLE titles ( `emp_no` int(11) NOT NULL, `title` varchar(50) NOT NULL, `from_date` date NOT NULL, `to_date` date DEFAULT NULL); INSERT INTO departments VALUES('d001','Marketing'); INSERT INTO departments VALUES('d002','Finance'); INSERT INTO dept_emp VALUES(10001,'d001','1986-06-26','9999-01-01'); INSERT INTO dept_emp VALUES(10002,'d001','1996-08-03','9999-01-01'); INSERT INTO dept_emp VALUES(10003,'d002','1995-12-03','9999-01-01'); INSERT INTO titles VALUES(10001,'Senior Engineer','1986-06-26','9999-01-01'); INSERT INTO titles VALUES(10002,'Staff','1996-08-03','9999-01-01'); INSERT INTO titles VALUES(10003,'Senior Engineer','1995-12-03','9999-01-01');
参考答案
SELECT d.dept_no, d.dept_name, t1.title, COUNT(t1.title) AS 'count' FROM (SELECT de.emp_no, de.dept_no, t.title FROM dept_emp AS de JOIN titles AS t --整理出含有title的表 ON de.emp_no = t.emp_no WHERE de.to_date = '9999-01-01' ) AS t1 JOIN departments AS d --联合department表 ON t1.dept_no = d.dept_no GROUP BY dept_no, title --分组 ORDER BY dept_no, title --排序