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 IF NOT EXISTS `titles` ( `emp_no` int(11) NOT NULL, `title` varchar(50) NOT NULL, `from_date` date NOT NULL, `to_date` date DEFAULT NULL);
输入描述:
无
输出描述:
dept_no | dept_name | title | count |
---|---|---|---|
d001 | Marketing | Senior Engineer | 1 |
d001 | Marketing | Staff | 1 |
d002 | Finance | Senior Engineer | 1 |
d003 | Human Resources | Senior Staff | 1 |
d004 | Production | Senior Engineer | 2 |
d005 | Development | Senior Staff | 1 |
d006 | Quality Management | Engineer | 2 |
d006 | Quality Management | Senior Engineer | 1 |
思路:看创建的表以及结果:tiltle是惟一的,需要的是 departments表和title表里面的dept_no,dept_name和title以及title的重复计数,但是departments和title表没有直接关系, 1.连接dept_emp和titles表,判断to_data=‘9999-01-01’ ,d.emp_no=t.emp_no 2.连接department和1操作之后的表,条件dept_no== 3.group by dept_no,title
SELECT de.dept_no, dp.dept_name, t.title, COUNT(t.title) AS countFROM titles AS t INNER JOIN dept_emp AS de ON t.emp_no = de.emp_no AND de.to_date = '9999-01-01' AND t.to_date = '9999-01-01'INNER JOIN departments AS dp ON de.dept_no = dp.dept_noGROUP BY de.dept_no, t.title
select dp.dept_no, dp.dept_name, t.title, count(t.title) as count from titles as t inner join dept_emp as deon t.emp_no = de.emp_no and t.to_date = '9999-01-01'and de.to_date = '9999-01-01'inner join departments as dpon de.dept_no = dp.dept_nogroup by t.title ,de.dept_no --group by 后面的顺序修改,输出顺序不同,不是输出描述中所需要的表,导致出错不通过