题目描述:
汇总各个部门当前员工(to_date='9999-01-01')的title类型的分配数目,
结果给出部门编号dept_no、dept_name、
其当前员工所有的title以及该类型title对应的数目count
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 enior Engineer 1
思路:
1.先查询出所有部门中员工的title,输出数据dept_no和title
select de.dept_no,t.title from dept_emp de,titles t
where de.emp_no=t.emp_no
and de.to_date='9999-01-01'
and t.to_date='9999-01-01'
2.再与部门表进行关联查询,对部门和title进行分组
参考答案:
select ds.dept_no,ds.dept_name,A.title,count(A.title) as count
from departments ds
inner join
(select de.dept_no,t.title from dept_emp de,titles t
where de.emp_no=t.emp_no
and de.to_date='9999-01-01'
and t.to_date='9999-01-01'
) A
on ds.dept_no=A.dept_no
group by ds.dept_no,A.title
网友评论