博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
【sql】部门最高工资 Department Highest Salary
阅读量:6112 次
发布时间:2019-06-21

本文共 2123 字,大约阅读时间需要 7 分钟。

  hot3.png

问题:

The Employee table holds all employees. Every employee has an Id, a salary, and there is also a column for the department Id.

+----+-------+--------+--------------+| Id | Name  | Salary | DepartmentId |+----+-------+--------+--------------+| 1  | Joe   | 70000  | 1            || 2  | Henry | 80000  | 2            || 3  | Sam   | 60000  | 2            || 4  | Max   | 90000  | 1            |+----+-------+--------+--------------+

The Department table holds all departments of the company.

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

Write a SQL query to find employees who have the highest salary in each of the departments. For the above tables, Max has the highest salary in the IT department and Henry has the highest salary in the Sales department.

+------------+----------+--------+| Department | Employee | Salary |+------------+----------+--------+| IT         | Max      | 90000  || Sales      | Henry    | 80000  |+------------+----------+--------+

解决:

① 让两个表内交起来,然后将结果表需要的列都标明,然后就是要找最高的薪水,我们用Max关键字来实现。2299 ms

SELECT d.Name Department,e1.Name Employee,e1.Salary Salary

FROM Employee e1 JOIN Department d ON e1.DepartmentId = d.Id
WHERE e1.Salary IN
(SELECT MAX(Salary) FROM Employee e2 WHERE e1.DepartmentId = e2.DepartmentId);/*不能用GROUP BY 对其进行分组。。。*/

② 不用Join关键字,直接用Where将两表连起来。1526 ms

SELECT d.Name Department,e1.Name Employee,e1.Salary Salary

FROM Employee e1,Department d
WHERE e1.DepartmentId = d.Id 
AND e1.Salary
(SELECT MAX(Salary) FROM Employee e2 WHERE e2.DepartmentId = d.Id);/*括号内的条件为e1时,得到的是一组数,为d时,得到的是一个值*/

③ 不用MAX方法而是用>=。 1187 ms

SELECT d.Name AS Department, e.Name AS Employee, e.Salary

FROM Employee e, Department d
WHERE e.DepartmentId = d.Id 
AND e.Salary >= ALL (SELECT Salary FROM Employee e2 WHERE e2.DepartmentId = d.Id);/*使用ALL是因为子查询语句会返回不止一行数据,使用ALL会与返回的每一个数据进行比较*/

SELECT d.Name Department, e1.Name Employee, e1.Salary

FROM Employee e1, Department d
WHERE e1.DepartmentId = d.Id 
AND e1.Salary >= ALL(SELECT Salary FROM Employee e2 WHERE e2.DepartmentId = e1.DepartmentId);

转载于:https://my.oschina.net/liyurong/blog/1570853

你可能感兴趣的文章
修改GRUB2背景图片
查看>>
Ajax异步
查看>>
好记性不如烂笔杆-android学习笔记<十六> switcher和gallery
查看>>
JAVA GC
查看>>
codeforce 599B Spongebob and Joke
查看>>
3springboot:springboot配置文件(外部配置加载顺序、自动配置原理,@Conditional)
查看>>
9、Dubbo-配置(4)
查看>>
前端第七天
查看>>
BZOJ 2190[SDOI2008]仪仗队
查看>>
图解SSH原理及两种登录方法
查看>>
[转载] 七龙珠第一部——第058话 魔境圣地
查看>>
【总结整理】JQuery基础学习---样式篇
查看>>
查询个人站点的文章、分类和标签查询
查看>>
基础知识:数字、字符串、列表 的类型及内置方法
查看>>
JSP的隐式对象
查看>>
P127、面试题20:顺时针打印矩阵
查看>>
JS图片跟着鼠标跑效果
查看>>
[SCOI2005][BZOJ 1084]最大子矩阵
查看>>
学习笔记之Data Visualization
查看>>
Leetcode 3. Longest Substring Without Repeating Characters
查看>>