查找所有员工自入职以来的薪水涨幅情况,给出员工编号emp_no以及其对应的薪水涨幅growth,并按照growth进行升序

题目描述

查找所有员工自入职以来的薪水涨幅情况,给出员工编号emp_no以及其对应的薪水涨幅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`));

输入描述:

输出描述:

 
emp_no growth
10011 0
省略 省略
10010 54496
10004 34003

示例1

输入

复制

输出

复制

--查找所有员工自入职以来的薪水涨幅情况,
--给出员工编号emp_no以及其对应的薪水涨幅growth,并按照growth进行升序
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;
--第二种方法
SELECT
	a.emp_no,
	( b.salary - c.salary ) AS growth 
FROM
	employees AS a
	INNER JOIN salaries AS b ON a.emp_no = b.emp_no 
	AND b.to_date = '9999-01-01'
	INNER JOIN salaries AS c ON a.emp_no = c.emp_no 
	AND a.hire_date = c.from_date 
ORDER BY
	growth ASC;
 
 
 

你可能感兴趣的:(mysql,牛客网练习,知识积累)