----SQL220 汇总各个部门当前员工的title类型的分配数目
汇总各个部门当前员工的title类型的分配数目,即结果给出部门编号dept_no、dept_name、其部门下所有的员工的title以及该类型title对应的数目count,结果按照dept_no升序排序,dept_no一样的再按title升序排序 ;
输出顺序:dept_no dept_name title count
表的创建及数据从插入:
sql
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 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 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');
查询思路:
① 所查数据涉及三表,需要三表连接查询 - join
② 统计title的个数,需要使用Count( )函数
③ 各个部门当前员工的title类型,需要对部门号和title分组
查询:
sql
select d.dept_no,dept_name,title,count(title) as count
from departments d
join dept_emp de on d.dept_no = de.dept_no
join titles t on de.emp_no = t.emp_no
group by d.dept_no,dept_name,title
order by d.dept_no,title