26. 彙總各個部門當前員工的title型別的分配數目
題目描述
彙總各個部門當前員工的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 |
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 |
SELECT
d.dept_no,
dept.dept_name,
t.title,
count(d.emp_no) AS `count`
FROM
(
dept_emp d
INNER JOIN titles t ON d.emp_no = t.emp_no
AND d.to_date = '9999-01-01'
AND t.to_date = '9999-01-01'
)
NATURAL LEFT JOIN departments dept
GROUP BY
d.dept_no,
t.title;