Write a SQL query to get the second highest salary from the Employee table.
编写SQL查询语句从Employee表中获得第二高的薪资
+----+--------+
| 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.
例如,给了上面的Employee表,第二高查询结果应该返回200,如果没有第二高的薪资,就返回null
+---------------------+
| SecondHighestSalary |
+---------------------+
| 200 |
+---------------------+
Write your MySQL query statement below
null
Custom Testcase
{
"headers": {
"Employee": [
"Id",
"Salary"
]
},
"rows": {
"Employee": [
[
1,
100
],
[
2,
200
],
[
3,
300
]
]
}
}
在Discuss区发现了几种答案
SELECT max(Salary) AS SecondHighestSalary
FROM Employee
WHERE Salary < (SELECT max(Salary) FROM Employee)
SELECT distinct(SecondHighestSalary) FROM Employee
Union
select null
ORDER BY SecondHighestSalary DESC LIMIT 1,1
select IFNULL(
(
select distinct e1.salary from Employee e1
where (
select count(distinct e2.salary )
from Employee e2
where e2.salary > e1.salary
) = 1
)
, null
) AS SecondHighestSalary
Here is my solution,you can change =1 to =2,=3 if you want to get the third highest or fourth
有人说 Simple query which handles the NULL situation,这是处理Null情况的简单查询,还有人提问说扩展性第2、第3的情况
max
:MAX 函数返回一列中的最大值。NULL 值不包括在计算中。
SELECT MAX(column_name) FROM table_name
MIN 和 MAX 也可用于文本列,以获得按字母顺序排列的最高或最低值
distinct
:用于返回唯一不同的值。
SELECT DISTINCT 列名称 FROM 表名称
Union
:UNION 操作符用于合并两个或多个 SELECT 语句的结果集。
请注意,UNION 内部的 SELECT 语句必须拥有相同数量的列。列也必须拥有相似的数据类型。同时,每条 SELECT 语句中的列的顺序必须相同。
SELECT column_name(s) FROM table_name1
UNION
SELECT column_name(s) FROM table_name2
默认地,UNION 操作符选取不同的值。如果允许重复的值,请使用 UNION ALL。另外,UNION 结果集中的列名总是等于 UNION 中第一个 SELECT 语句中的列名。
DESC
/ASC
:降序/升序
ORDER BY 语句用于根据指定的列对结果集进行排序。
ORDER BY 语句默认按照升序对记录进行排序。
SELECT Company, OrderNumber FROM Orders ORDER BY Company DESC, OrderNumber ASC
LIMIT
:TOP 子句用于规定要返回的记录的数目。
对于拥有数千条记录的大型表来说,TOP 子句是非常有用的。
注释:并非所有的数据库系统都支持 TOP 子句。
SELECT TOP number|percent column_name(s)
FROM table_name
SELECT column_name(s)
FROM table_name
LIMIT number
IFNULL