- ~
題目描述
查找全部員工自入職以來的薪水漲幅狀況,給出員工編號emp_noy以及其對應的薪水漲幅growth,並按照growth進行升序
CREATE TABLE employees
(emp_no
int(11) NOT NULL,birth_date
date NOT NULL,first_name
varchar(14) NOT NULL,last_name
varchar(16) NOT NULL,gender
char(1) NOT NULL,hire_date
date NOT NULL,
PRIMARY KEY (emp_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
));spa
本題思路是先分別用兩次LEFT JOIN左鏈接employees與salaries,創建兩張表,分別存放員工當前工資(sCurrent)與員工入職時的工資(sStart),再用INNER JOIN鏈接sCurrent與sStart,最後限定在同一員工下用當前工資減去入職工資。 方法一:內層用LEFT JOIN,外層用INNER JOIN(內層也能夠改用 INNER JOIN) SELECT sCurrent.emp_no, (sCurrent.salary-sStart.salary) AS growth FROM (SELECT s.emp_no, s.salary FROM employees e LEFT JOIN salaries s ON e.emp_no = s.emp_no WHERE s.to_date = '9999-01-01') AS sCurrent INNER JOIN (SELECT s.emp_no, s.salary FROM employees e LEFT JOIN salaries s ON e.emp_no = s.emp_no WHERE s.from_date = e.hire_date) AS sStart ON sCurrent.emp_no = sStart.emp_no ORDER BY growth 方法二:內外都層用FROM並列查詢 SELECT sCurrent.emp_no, (sCurrent.salary-sStart.salary) AS growth FROM (SELECT s.emp_no, s.salary FROM employees e, salaries s WHERE e.emp_no = s.emp_no AND s.to_date = '9999-01-01') AS sCurrent, (SELECT s.emp_no, s.salary FROM employees e, salaries s WHERE e.emp_no = s.emp_no AND s.from_date = e.hire_date) AS sStart WHERE sCurrent.emp_no = sStart.emp_no ORDER BY growth