博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
leetcode-Second Highest Salary
阅读量:7101 次
发布时间:2019-06-28

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

Write a SQL query to get the second highest salary from the Employee table.

+----+--------+| Id | Salary |+----+--------+| 1  | 100    || 2  | 200    || 3  | 300    |+----+--------+

For example, given the above Employee table, the second highest salary is 200. If there is no second highest salary, then the query should return null.


思路:

如果是选出所有Salary中最大的,语句是:

select max(Salary)from Employee

(*)

//

第二种方法,用到两个核心知识点:

select case when count(Salary) > 1then (    select distinct Salary    from Employee    order by Salary desc    limit 1,1)else nullend from Employee

(1)case when

 

(2)limit

limit m,n的含义是从选出该列从第m行开始的n行数元组

如果写个Select * from table limit 5, 10,很难一样就看出来到底哪个是limit,哪个是offset。我觉得应该尽量避免这种写法,需要offset的,就采用严谨的Select * from table limit 10 offset 5这样的格式;对于offset是0的,则直接省略,就写Select * from table limit 10好了。

//

理解了(*),那么第二大的就是在除去最大的Salary中选择最大的Salary

同样的道理,我们可以选出第三大的和第四大的etc.

选择第三大的代码如下:

select max(Salary)from Employeewhere salary < (     select max(Salary)     from Employee     where Salary <>      (selcet max(Salary) from Employee))

 或者是:

select max(Salary)from Employeewhere Salary <> (select max(Salary)from Employee)and Salary <>(select max(Salary)from Employeewhere Salary<>(select max(Salary) from Employee) )

select max(Salary)from Employeewhere Salary < (select max(Salary) from Employee)

 

转载于:https://www.cnblogs.com/immortal-worm/p/5078809.html

你可能感兴趣的文章
深入分析Spring 与 Spring MVC容器
查看>>
在已有元素后面插入一个新元素,属于通用型函数insertAfter(newElement,targetElement)...
查看>>
lesson6-表
查看>>
来自二维世界的忧愁:如何避免康康的悲剧再次重演?
查看>>
传教士与野人过河问题
查看>>
.NET Framework 3.5 Common Namespaces and Types Poster
查看>>
Winform应用程序实现通用遮罩层
查看>>
python+uwsgi导致redis无法长链接引起性能下降问题记录
查看>>
对linux安全设置中需要注意和掌握的地方
查看>>
HDFS-Architecture剖析
查看>>
百花齐放,繁荣和瓶颈同在,2016年VR AR产业梳理
查看>>
Jira 6.3.6使用openldap进行认证——方法一
查看>>
项目经理成长日记(10)——百万大侠,能否推敲
查看>>
oracle之 SYSAUX表空间维护
查看>>
thinkphp-条件判断-范围判断-in与else
查看>>
搜狗智能联想输入法,背后的运维又是如何智能的?
查看>>
就绪IT平台 走进智能企业——智能化浪潮中的领军者大型系列报道
查看>>
Shader的函数公式以及使用的场景
查看>>
3Python全栈之路系列之D
查看>>
js self = this的解释
查看>>