Score
0
Watch 44 Star 256 Fork 69

xuthus / 数据库SQL实战SQLMIT

Create your Gitee Account
Explore and code with more than 6 million developers,Free private repositories !:)
Sign up
Clone or download
22.统计各个部门对应员工涨幅的次数总和.md 1.35 KB
Copy Edit Web IDE Raw Blame History
xuthus authored 2019-08-03 23:19 . add:22-25

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

题目描述

统计各个部门对应员工涨幅的次数总和,给出部门编码dept_no、部门名称dept_name以及次数sum

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总和

Comment ( 0 )

Sign in for post a comment