一.查找employees表emp_no与last_name的员工信息
实现SQL
select
*
from
employees
where
emp_no % 2 ! = 0
and last_name <> 'Mary'
order by
hire_date desc
二.统计出当前各个title类型对应的员工当前薪水对应的平均工资
实现SQL
select
t.title,
avg(s.salary)
from
titles t
inner join salaries s on t.emp_no = s.emp_no
group by
t.title
三.获取当前薪水第二多的员工的emp_no以及其对应的薪水salary
实现SQL
select
emp_no,
salary
from
salaries
where
salary = (
select
salary
from
salaries
group by
salary
order by
salary desc
limit
1, 1
)
四. 获取当前薪水第二多的员工的emp_no以及其对应的薪水salary
实现SQL
select
s.emp_no,
s.salary,
e.last_name,
e.first_name
from
salaries s
join employees e on s.emp_no = e.emp_no
where
s.salary = (
select
max(salary)
from
salaries
where
salary < (
select
max(salary)
from
salaries
)
)
五.查找所有员工的last_name和first_name以及对应的dept_name
实现SQL
select
e.last_name,
e.first_name,
t.dept_name
from
employees e
left join (
select
emp.emp_no,
d.dept_name
from
departments d
left join dept_emp emp on emp.dept_no = d.dept_no
) as t on e.emp_no = t.emp_no;
六.查找在职员工自入职以来的薪水涨幅情况
实现SQL
select
b.emp_no,
(b.salary - a.salary) as growth
from
(
select
e.emp_no,
s.salary
from
employees e
left join salaries s on e.emp_no = s.emp_no
and e.hire_date = s.from_date
) a -- 入职工资表
inner join (
select
e.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'
) b -- 现在工资表
on a.emp_no = b.emp_no
order by
growth
七.统计各个部门的工资记录数
实现SQL
select
depart.dept_no,
depart.dept_name,
count(temp.emp_no) as sum
from
departments depart
left join (
select
d.emp_no,
d.dept_no,
s.salary
from
dept_emp d
left join salaries s on d.emp_no = s.emp_no
) as temp on depart.dept_no = temp.dept_no
group by
depart.dept_no
八.对所有员工的薪水按照salary降序进行1-N的排名
实现SQL
select
emp_no,
salary,
dense_rank() over(
order by
salary desc
) as t_rank
from
salaries
order by
t_rank,
emp_no asc
窗口函数用法:
<窗口函数> OVER ( [PARTITION BY <列清单> ]
ORDER BY <排序用列清单> )
*其中[ ]中的内容可以忽略
下面介绍三种用于进行排序的专用窗口函数:
1、RANK()
在计算排序时,若存在相同位次,会跳过之后的位次。
例如,有3条排在第1位时,排序为:1,1,1,4······
2、DENSE_RANK()
这就是题目中所用到的函数,在计算排序时,若存在相同位次,不会跳过之后的位次。
例如,有3条排在第1位时,排序为:1,1,1,2······
3、ROW_NUMBER()
这个函数赋予唯一的连续位次。
例如,有3条排在第1位时,排序为:1,2,3,4······
九.获取所有非manager员工当前的薪水情况
实现SQL
select
d.dept_no,
d.emp_no,
s.salary
from
dept_emp d
left join salaries s on d.emp_no = s.emp_no
where
d.emp_no not in (
select
emp_no
from
dept_manager
)
十.获取员工其当前的薪水比其manager当前薪水还高的相关信息
实现SQL
select
temp.emp_no,
d.emp_no as manager_no,
temp.salary as emp_salary,
temp1.salary as manager_salary
from
dept_manager d
left join (
select
e.emp_no,
e.dept_no,
s.salary
from
dept_emp e,
salaries s
where
e.emp_no = s.emp_no
) as temp on temp.dept_no = d.dept_no
left join (
select
e.emp_no,
e.dept_no,
s.salary
from
dept_manager e,
salaries s
where
e.emp_no = s.emp_no
) as temp1 on temp1.dept_no = d.dept_no
where
temp.emp_no not in (
select
emp_no
from
dept_manager
)
and temp.salary > temp1.salary;