61 Star 427 Fork 145

xuthus / 数据库SQL实战

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
26.汇总各个部门当前员工的title类型的分配数目.md 1.62 KB
一键复制 编辑 原始数据 按行查看 历史
xuthus 提交于 2019-08-12 23:23 . add:all

汇总各个部门当前员工的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);

答案

select d.dept_no,d.dept_name,title,count(emp_no) count from (select emp_no,d.dept_no,title,dept_name from (select de.emp_no,dept_no,title from dept_emp de,titles t where de.emp_no = t.emp_no and t.to_date = '9999-01-01' and de.to_date = '9999-01-01') t1,departments d where t1.dept_no = d.dept_no) t1,departments d where t1.dept_no = d.dept_no group by t1.dept_no,title

题解

1、当前员工对用的title

select de.emp_no,dept_no,title from dept_emp de,titles t where de.emp_no = t.emp_no and t.to_date = '9999-01-01' and de.to_date = '9999-01-01'

2、当前员工对应的dept信息

select emp_no,d.dept_no,title,dept_name from (select de.emp_no,dept_no,title from dept_emp de,titles t where de.emp_no = t.emp_no and t.to_date = '9999-01-01' and de.to_date = '9999-01-01') t1,departments d where t1.dept_no = d.dept_no

3、罗列title对应的count,对dept_no和title进行分组

SQL
1
https://gitee.com/xuthus5/Database-SQL-Actual-Combat.git
git@gitee.com:xuthus5/Database-SQL-Actual-Combat.git
xuthus5
Database-SQL-Actual-Combat
数据库SQL实战
master

搜索帮助