力扣資料庫題目176第二高的薪水
阿新 • • 發佈:2020-12-04
力扣資料庫題目176第二高的薪水
題目
編寫一個 SQL 查詢,獲取 Employee 表中第二高的薪水(Salary) 。
+----+--------+
| Id | Salary |
+----+--------+
| 1 | 100 |
| 2 | 200 |
| 3 | 300 |
+----+--------+
例如上述 Employee 表,SQL查詢應該返回 200 作為第二高的薪水。如果不存在第二高的薪水,那麼查詢應返回 null。
+---------------------+
| SecondHighestSalary |
+---------------------+
| 200 |
+---------------------+
來源:力扣(LeetCode)
方案一
SELECT salary SecondHighestSalary
FROM (
SELECT DISTINCT salary FROM test.employee
UNION ALL
SELECT NULL
UNION ALL
SELECT NULL
) t ORDER BY salary DESC LIMIT 1,1
方案二
SELECT salary SecondHighestSalary FROM ( SELECT salary,DENSE_RANK() OVER(ORDER BY salary DESC) num FROM test.employee UNION ALL SELECT NULL,2 UNION ALL SELECT NULL,2 ) t WHERE num = 2 LIMIT 1;
方案三
SELECT t.salary SecondHighestSalary
FROM (
SELECT salary
FROM test.employee
WHERE salary < (
SELECT MAX(salary)
FROM test.employee
)
UNION ALL
SELECT NULL
) t
ORDER BY t.salary DESC LIMIT 1
方案四
SELECT t.salary SecondHighestSalary FROM ( SELECT salary FROM test.employee WHERE salary < ANY( SELECT salary FROM test.employee ) UNION ALL SELECT NULL ) t ORDER BY t.salary DESC LIMIT 1
方案五
SELECT (SELECT salary
FROM (
SELECT DISTINCT salary FROM test.employee
) t ORDER BY salary DESC LIMIT 1,1)SecondHighestSalary
方案六
SELECT (SELECT salary
FROM (
SELECT salary,DENSE_RANK() OVER(ORDER BY salary DESC) num
FROM test.employee
) t
WHERE num = 2
LIMIT 1) SecondHighestSalary
方案七
SELECT (SELECT t.salary
FROM (
SELECT salary
FROM test.employee
WHERE salary < (
SELECT MAX(salary)
FROM test.employee
)
) t
ORDER BY t.salary DESC LIMIT 1) SecondHighestSalary
方案八
SELECT (SELECT t.salary
FROM (
SELECT salary
FROM test.employee
WHERE salary < ANY(
SELECT salary
FROM test.employee
)
) t
ORDER BY t.salary DESC LIMIT 1) SecondHighestSalary
分析
題目要求的結果是一行一列,並保證兩個條件
1、列別名SecondHighestSalary
2、行至少一行NULL,為了維持這個問題
前四個方案是製造出來一個NULL行,後四個方案是0行使用select ()子查詢後造出NULL行
為了保證條件2,廢了很多事。
方案一五使用distinct,二六使用的開窗,三七使用的子查詢,四八使用的ANY
建表
CREATE TABLE `employee` (
`id` int NOT NULL AUTO_INCREMENT,
`salary` int NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=InnoDB COLLATE=utf8mb4_0900_ai_ci;
資料初始化
INSERT INTO `test`.employee(`id`,`salary`)
VALUES(1,100),(2,200),(3,300)