## xuthus / 数据库SQL实战SQLMIT

Explore and code with more than 6 million developers，Free private repositories ！：）
22.统计各个部门对应员工涨幅的次数总和.md 1.35 KB
xuthus authored 2019-08-03 23:19 . add:22-25

# 统计各个部门对应员工涨幅的次数总和

## 题目描述

```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 `salaries` (
`emp_no` int(11) NOT NULL,
`salary` int(11) NOT NULL,
`from_date` date NOT NULL,
`to_date` date NOT NULL,
PRIMARY KEY (`emp_no`,`from_date`));```

## 答案

`select dept_no,dept_name,sum(sum) sum from (select emp_no,d.dept_no,dept_name from dept_emp de left join departments d on de.dept_no = d.dept_no) info inner join (select emp_no,count(salary) sum from salaries s group by emp_no) s on info.emp_no = s.emp_no group by dept_no`

## 题解

1、计算每个员工的涨幅次数总和 s

```-- 涨幅次数总和
(select emp_no,count(salary) sum from salaries s group by emp_no) s```

2、拼接员工和部门信息 info

```-- 部门信息
(select emp_no,d.dept_no,dept_name from dept_emp de left join departments d on de.dept_no = d.dept_no) info```

3、拼接info和s表，对dept_no进行分组，计算每个部门对应的sum总和