力扣数据库题目176第二高的薪水
题目
编写一个 SQL 查询,获取 Employee 表中第二高的薪水(Salary) 。
+----+--------+
| Id | Salary |
+----+--------+
| 1 | 100 |
| 2 | 200 |
| 3 | 300 |
+----+--------+
例如上述 Employee 表,SQL查询应该返回 200 作为第二高的薪水。如果不存在第二高的薪水,那么查询应返回 null。
+---------------------+
| SecondHighestSalary |
+---------------------+
| 200 |
+---------------------+
来源:力扣(LeetCode)
方案一
SELECT salary SecondHighestSalaryFROM ( 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 ) tWHERE num = 2LIMIT 1;
方案三
SELECT t.salary SecondHighestSalaryFROM ( SELECT salary FROM test.employee WHERE salary < ( SELECT MAX(salary) FROM test.employee ) UNION ALL SELECT NULL ) tORDER BY t.salary DESC LIMIT 1
方案四
SELECT t.salary SecondHighestSalaryFROM ( SELECT salary FROM test.employee WHERE salary < ANY( SELECT salary FROM test.employee ) UNION ALL SELECT NULL ) tORDER 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 ) tWHERE num = 2LIMIT 1) SecondHighestSalary
方案七
SELECT (SELECT t.salary FROM ( SELECT salary FROM test.employee WHERE salary < ( SELECT MAX(salary) FROM test.employee ) ) tORDER 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 ) ) tORDER 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)
原文转载:http://www.shaoqun.com/a/494852.html
prime:https://www.ikjzd.com/w/129
斑马物流:https://www.ikjzd.com/w/1316
二类电商:https://www.ikjzd.com/w/1457
力扣数据库题目176第二高的薪水题目编写一个SQL查询,获取Employee表中第二高的薪水(Salary)。+----+--------+|Id|Salary|+----+--------+|1|100||2|200||3|300|+----+--------+例如上述Employee表,SQL查询应该返回200作为第二高的薪水。如果不存在第二高的薪水,那么查询应返回null。+--------
中国邮政邮乐网:中国邮政邮乐网
敦煌网:敦煌网
四姑娘山特产介绍 - :四姑娘山特产介绍 -
WishPost更新域名,6月14日15时起生效!:WishPost更新域名,6月14日15时起生效!
(细节操作)instagram引流Amazon,:(细节操作)instagram引流Amazon,
没有评论:
发表评论