-
Notifications
You must be signed in to change notification settings - Fork 0
/
DB 176. Second Highest Salary
91 lines (75 loc) · 2.28 KB
/
DB 176. Second Highest Salary
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
Create table If Not Exists Employee (id int, salary int)
Truncate table Employee
insert into Employee (id, salary) values ('1', '100')
insert into Employee (id, salary) values ('2', '200')
insert into Employee (id, salary) values ('3', '300')
Table: Employee
+-------------+------+
| Column Name | Type |
+-------------+------+
| id | int |
| salary | int |
+-------------+------+
id is the primary key column for this table.
Each row of this table contains information about the salary of an employee.
Write an SQL query to report the second highest salary from the Employee table.
If there is no second highest salary, the query should report null.
The query result format is in the following example.
explain this question in chinese and write sql code, and explain it by notes
line by line
Example 1:
Input:
Employee table:
+----+--------+
| id | salary |
+----+--------+
| 1 | 100 |
| 2 | 200 |
| 3 | 300 |
+----+--------+
Output:
+---------------------+
| SecondHighestSalary |
+---------------------+
| 200 |
+---------------------+
Example 2:
Input:
Employee table:
+----+--------+
| id | salary |
+----+--------+
| 1 | 100 |
+----+--------+
Output:
+---------------------+
| SecondHighestSalary |
+---------------------+
| null |
+---------------------+
题目要求查询员工表中第二高的工资。如果没有第二高的工资,查询结果应为 null。
下面是 SQL 查询代码:
sql
SELECT (
SELECT DISTINCT salary
FROM Employee
ORDER BY salary DESC
LIMIT 1 OFFSET 1
) AS SecondHighestSalary
FROM Employee
LIMIT 1;
该代码的注释如下:
SELECT DISTINCT salary:查询员工表中不同的工资值
FROM Employee:从员工表中查询数据
ORDER BY salary DESC:按工资值降序排列
LIMIT 1 OFFSET 1:从排序后的结果中选择第二个数据(从零开始计数)
AS SecondHighestSalary:将查询结果命名为 SecondHighestSalary
FROM Employee:从员工表中查询数据
LIMIT 1:仅返回查询结果的第一行
该代码通过使用内部查询和排序,从员工表中查询第二高的工资。如果第二高的工资不存在则查询结果为 null。
best code
select max(salary) as SecondHighestSalary
from Employee
where salary != (
select max(salary) from Employee
)