- ~
統計各個部門對應員工漲幅的次數總和,給出部門編碼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
));編碼
本題關鍵是要將 每一個部門分組,並分別統計工資記錄總數,思路以下: 一、用INNER JOIN鏈接dept_emp表和salaries表,並以dept_emp.no分組,統計每一個部門全部員工工資的記錄總數 二、再將上表用INNER JOIN鏈接departments表,限制條件爲兩表的dept_no相等,找到dept_no與dept_name的對應關係,最後依次輸出dept_no、dept_name、sum SELECT de.dept_no, dp.dept_name, COUNT(s.salary) AS sum FROM (dept_emp AS de INNER JOIN salaries AS s ON de.emp_no = s.emp_no) INNER JOIN departments AS dp ON de.dept_no = dp.dept_no GROUP BY de.dept_no