力扣數據庫題目176第二高的薪水mysql
編寫一個 SQL 查詢,獲取 Employee 表中第二高的薪水(Salary) 。sql
+----+--------+
| Id | Salary |
+----+--------+
| 1 | 100 |
| 2 | 200 |
| 3 | 300 |
+----+--------+
例如上述 Employee 表,SQL查詢應該返回 200 做爲第二高的薪水。若是不存在第二高的薪水,那麼查詢應返回 null。數據庫
+---------------------+
| SecondHighestSalary |
+---------------------+
| 200 |
+---------------------+code
來源:力扣(LeetCode)blog
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
題目要求的結果是一行一列,並保證兩個條件ci
一、列別名SecondHighestSalaryclass
二、行至少一行NULL,爲了維持這個問題test
前四個方案是製造出來一個NULL行,後四個方案是0行使用select ()子查詢後造出NULL行select
爲了保證條件2,廢了不少事。im
方案一五使用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)