select
*
from
employees
where
emp_no % 2 ! = 0
and last_name <> 'Mary'
order by
hire_date desc
select
t.title,
avg(s.salary)
from
titles t
inner join salaries s on t.emp_no = s.emp_no
group by
t.title
select
emp_no,
salary
from
salaries
where
salary = (
select
salary
from
salaries
group by
salary
order by
salary desc
limit
1, 1
)
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
)
)
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;
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
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
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······
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
)
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;