LeetCode Database #176 Second Highest Salary

LeetCode Database #176 Second Highest Salary

个人比较喜欢小写SQL代码,反正可以写完再格式化

题目内容

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 query should return 200 as the second highest salary. If there is no second highest salary, then the query should return null.

+---------------------+
| SecondHighestSalary |
+---------------------+
| 200                 |
+---------------------+

解题

选出第二大的薪水,肯定要做的是排序order by Salary desc,再使用limit 1 offset 1来选出第二大的(这个不看solution我还真不知道,数据库还是学的太少)

select distinct Salary as SecondHighestSalary
from Employee
order by Salary desc
limit 1 offset 1;

但是直接这样提交是错误的,因为题目要求当没有结果时返回null,而空集并不等于null,参考solution,有两种方法。

第一种是使用ifnull(expr1, expr2)函数,如果expr1不为null返回expr1,否则返回expr2。所以可以写作

select ifnull((
    select distinct Salary
    from Employee
    order by Salary desc
    limit 1 offset 1), 
    null) as SecondHighestSalary;

第二种比较骚,select一个空集的结果为null。写作

select (
    select distinct Salary
    from Employee
    order by Salary desc
    limit 1 offset 1) as SecondHighestSalary;
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值