sql-面试题

1 篇文章 0 订阅

SQL查询每个部门工资前三名的员工信息

1、单个表 

+----+-------+--------+--------------+
| Id | eName  | Sal   | deptno       |
+----+-------+--------+--------------+
| 1  | Joe   | 70000  | 1            |
| 2  | Henry | 80000  | 2            |
| 3  | Sam   | 60000  | 2            |
| 4  | Max   | 90000  | 1            |
| 5  | Janet | 69000  | 1            |
| 6  | Randy | 85000  | 1            |
+----+-------+--------+--------------+

通用sql

select deptno, ename, sal      
from emp e1     
where      
   (  
    select count(1)     
    from emp e2     
    where e2.deptno=e1.deptno and e2.sal>=e1.sal  
   ) <=3 /*这里的数值表示你想取前几名*/  
order by deptno, sal desc;
oracle查询
select * from         
 (select deptno,ename,sal,row_number() over (partition by deptno        
    order by sal desc) rn         
 from emp)         
    where rn<3;

2、两表关联

表Employee:

+----+-------+--------+--------------+
| Id | Name  | Salary | DepartmentId |
+----+-------+--------+--------------+
| 1  | Joe   | 70000  | 1            |
| 2  | Henry | 80000  | 2            |
| 3  | Sam   | 60000  | 2            |
| 4  | Max   | 90000  | 1            |
| 5  | Janet | 69000  | 1            |
| 6  | Randy | 85000  | 1            |
+----+-------+--------+--------------+

表Department:

+----+----------+
| Id | Name     |
+----+----------+
| 1  | IT       |
| 2  | Sales    |
+----+----------+

 

Select a.Name as Department, b.Name as Employee, b.Salary 
from Department a, Employee b 
where b.DepartmentId = a.Id and (
  Select count(distinct Salary) From Employee where DepartmentId=a.Id and Salary > b.Salary
)<3
order by Department

oracle

select * from (select d.name,e.name,e.Salary,row_number() over (partition by e.DepartmentId        
order by Salary desc) rn         
from Employee e inner join Department d on e.DepartmentId = d.DepartmentId)
where rn<3;

转自:https://www.cnblogs.com/hxzblog/p/7307537.html
           https://www.cnblogs.com/wan1976/p/4766553.html

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值