sql自关联

select employee_id,department_id,salary from employees e where salary =(select max(salary) from employees m where m.department_id=e.department_id)
可查处每部门的最高工资,不知道他的执行顺序是什么样的

 

SELECT employee_id, department_id, salary
FROM employees e
WHERE salary = ( SELECT MAX( salary )
FROM employees m
WHERE m.department_id = e.department_id )

用类似PL/SQL的写法给你看看

代码:
   
   

declare
max_salary number;
begin
for e in
(SELECT employee_iddepartment_idsalary
  FROM employees 
loop
  select MAX
salary into max_salary
  FROM employees m
  WHERE m
.department_id e.department_id ;
  if (
e.salary max_salarythen 
  dbms_output
.put_line(e.employee_id||' ' ||e.department_id ||' '||e.salary);
  
end if;
end loop;
end;
/


对于employees e里的每行
检查 算出 和它的 department_id 一样的 employees m中最高Salary的数据。
如果 employees e 中的 Salary 和 相同department_id 一样的 employees m中最高Salary一致,则返回这一行。

整个语句等于是,找出所有在本部门中工资最高的个人,也可以写成:
select employee_id, department_id, salary from(
select employee_id, department_id, salary,
rank() over(partition by department_id order by salary desc ) as r
from employees
) where r= 1
可以避免多次访问 employees

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值