如何获得部门明智的最高工资和最高工资持有人员工姓名,考虑使用密钥连接3个表 IO / -
emptable, saltable,depttable
id name dept_id id sal dept_id dept_name
1 ram 10 1 100 10 xyz
2 sham 10 2 500 20 abc
3 jadu 20 3 900 30 por
4 john 20 4 999 40 stu
5 Madhu 30 5 300 50 xxx
O / P -
name,sal,dept_name
sham 500 abc
john 999 stu
Madhu300 xxx
答案 0 :(得分:1)
SELECT DISTINCT
MAX(amount) OVER (PARTITION BY d.id ORDER BY s.amount DESC) AS sal,
FIRST_VALUE(e.name) OVER (PARTITION BY d.id ORDER BY s.amount DESC) AS emp,
d.name as dept
FROM emptable e
INNER JOIN depttable d
ON e.dept_id = d.id
INNER JOIN saltable s
ON s.id = e.id
我对表中的列名做了一些假设。您可以找到我的架构脚本here。
答案 1 :(得分:0)
您可以加入所有表格,然后使用窗口函数row_number选择每个部门的前两个记录:
select *
from (
select t.*,
row_number() over (
partition by dept_id order by salary desc
) rn
from (
select e.*,
s.salaray,
d.dept_name
from emptable e
join saltable s on e.emp_id = s.emp_id
join depttable d on d.dept_id = e.dept_id
) t
) t
where rn <= 2;
您的表缺少列名称。所以,我假设名字(希望正确)