我有两个桌子。一个给员工
select
avg(notificationcount) as statistic_mean,
median(notificationcount) as statistic_median,
stats_mode(notificationcount) as statistic_mode
from mytable;
一个代表部门名称
LAST_NAME SALARY DEPARTMENT_ID
------------------------- ---------- -------------
Vargas 2500 50
Zlotkey 10500 50
Abel 11000 80
Taylor 8600 80
我想在employees表中选择薪水最高的前三名雇员,得到后我想获得他们的部门名。这样的结果。
DEPARTMENT_ID DEPARTMENT_NAME
------------- ------------------------------
50 Shipping
80 Sales
我尝试过:
LAST_NAME SALARY DEPARTMENT_NAME
------------------------- ---------- -------------
Abel 11000 Sales
Zlotkey 10500 Shipping
Taylor 8600 Sales
但是我不知道如何使用join来获取department_name。
平台:Windows10
SQLDeveloper版本:18.01
答案 0 :(得分:1)
您可以对子查询执行JOIN
:
SELECT e.LAST_NAME, e.SALARY, d.DEPARTMENT_NAME
FROM employees e INNER JOIN
department d
ON d.DEPARTMENT_ID = e.DEPARTMENT_ID
WHERE e.DEPARTMENT_ID = (SELECT e1.DEPARTMENT_ID
FROM employees e1
ORDER BY e1.SALARY DESC
FETCH FIRST 1 ROWS ONLY
);
编辑:如果只需要三名员工,则可以:
SELECT e.LAST_NAME, e.SALARY, d.DEPARTMENT_NAME
FROM employees e INNER JOIN
department d
ON d.DEPARTMENT_ID = e.DEPARTMENT_ID
ORDER BY e.SALARY DESC
FETCH FIRST 3 ROWS ONLY
答案 1 :(得分:1)
尝试
select top(3)LAST_NAME, SALARY, DEPARTMENT_NAME
from employees e
inner join department d on e.DEPARTMENT_ID = d.DEPARTMENT_ID
where d.DEPARTMENT_NAME = 'sales'
order by SALARY desc
答案 2 :(得分:1)
您可以使用窗口功能来做到这一点:
select e.last_name, e.salary, d.department_name
from (select e.*, max(sum_salary) over () as max_sum_salary
from (select e.*, sum(e.salary) over (partition by department_id) as sum_salary
from employees e
) e
) e join
department d
on e.department_id = d.department_id
where max_sum_salary = sum_salary