力扣資料庫題目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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/230261.html
標籤:其他
下一篇:MySQL主從同步及讀寫分離
