Sql笔试:查找员工编号emp_no为10001其自入职以来的薪水salary涨幅值growth

个人网站

题目描述
查找员工编号emp_no为10001其自入职以来的薪水salary涨幅值growth

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`));

输出描述:

 growth(涨幅值)
 28841 

解题思路
求编号10001号员工入职以来的薪水涨幅?
① 即10001号员工入职以来最大日期的薪水 salary_MAX_to_date
② 即10001号员工入职以来最小日期的薪水 salary_MIN_to_date
③ salary_MAX_to_date-salary_MIN_to_date AS growth

具体代码如下图所示

SELECT (
        (SELECT salary 
        FROM salaries 
        WHERE emp_no=10001 
        order by to_date DESC LIMIT 1) --AS salary_MAX_TO_DATE 
      - (SELECT salary 
         FROM salaries 
         WHERE emp_no=10001 order by to_date  LIMIT 1) --AS salary_MIN_TO_DATE
        ) AS growth

另一种思路
设定10001号员工入职以来一直处于加薪状态,最后一次调整薪水时没有被降薪
①即10001号员工入职以来最大薪水 MAX_salary
②即10001号员工入职以来最小薪水 MIN_salary
③MAX_salary – MIN_salary AS growth

具体代码如下图所示

SELECT MAX_salary-MIN_salary AS growth 
FROM 
    (SELECT emp_no,MAX(salary) AS MAX_salary  from salaries where emp_no=10001
    GROUP BY emp_no) AS A
    INNER JOIN 
    (select emp_no,MIN(salary) AS MIN_salary from salaries where emp_no=10001
    GROUP BY emp_no) AS B 
    ON A.emp_no = B.emp_no

你可能感兴趣的:(Sql笔试)