编写一个 SQL 查询,获取 Employee 表中第二高的薪水(Salary) 。
±—±-------+
| Id | Salary |
±—±-------+
| 1 | 100 |
| 2 | 200 |
| 3 | 300 |
±—±-------+
例如上述 Employee 表,SQL查询应该返回 200 作为第二高的薪水。如果不存在第二高的薪水,那么查询应返回 null。
±--------------------+
| SecondHighestSalary |
±--------------------+
| 200 |
±--------------------+
建表
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’)
查询语句:
SELECT
IFNULL((SELECT DISTINCT Salary
FROM Employee
ORDER BY Salary DESC
LIMIT 1,1), NULL)
AS SecondHighestSalary
编写一个 SQL 查询来实现分数排名。
如果两个分数相同,则两个分数排名(Rank)相同。请注意,平分后的下一个名次应该是下一个连续的整数值。换句话说,名次之间不应该有“间隔”。
±—±------+
| Id | Score |
±—±------+
| 1 | 3.50 |
| 2 | 3.65 |
| 3 | 4.00 |
| 4 | 3.85 |
| 5 | 4.00 |
| 6 | 3.65 |
±—±------+
例如,根据上述给定的 Scores 表,你的查询应该返回(按分数从高到低排列):
建表:
Create table If Not Exists Scores (id int, score DECIMAL(3,2))
Truncate table Scores
insert into Scores (id, score) values (‘1’, ‘3.5’)
insert into Scores (id, score) values (‘2’, ‘3.65’)
insert into Scores (id, score) values (‘3’, ‘4.0’)
insert into Scores (id, score) values (‘4’, ‘3.85’)
insert into Scores (id, score) values (‘5’, ‘4.0’)
insert into Scores (id, score) values (‘6’, ‘3.65’)
±------±-----+
| Score | Rank |
±------±-----+
| 4.00 | 1 |
| 4.00 | 1 |
| 3.85 | 2 |
| 3.65 | 3 |
| 3.65 | 3 |
| 3.50 | 4 |
±------±-----+
查询语句:
select score as “Score”,dense_rank() over (order by score desc) as “Rank” from scores;
表:Logs
±------------±--------+
| Column Name | Type |
±------------±--------+
| id | int |
| num | varchar |
±------------±--------+
id 是这个表的主键。
编写一个 SQL 查询,查找所有至少连续出现三次的数字。
返回的结果表中的数据可以按 任意顺序 排列。
查询结果格式如下面的例子所示:
Logs 表:
±—±----+
| Id | Num |
±—±----+
| 1 | 1 |
| 2 | 1 |
| 3 | 1 |
| 4 | 2 |
| 5 | 1 |
| 6 | 2 |
| 7 | 2 |
±—±----+
Result 表:
±----------------+
| ConsecutiveNums |
±----------------+
| 1 |
±----------------+
1 是唯一连续出现至少三次的数字。
建表:
Create table If Not Exists Logs (id int, num int)
Truncate table Logs
insert into Logs (id, num) values (‘1’, ‘1’)
insert into Logs (id, num) values (‘2’, ‘1’)
insert into Logs (id, num) values (‘3’, ‘1’)
insert into Logs (id, num) values (‘4’, ‘2’)
insert into Logs (id, num) values (‘5’, ‘1’)
insert into Logs (id, num) values (‘6’, ‘2’)
insert into Logs (id, num) values (‘7’, ‘2’)
查询语句:
select DISTINCT a.Num as ConsecutiveNums
from Logs as a,Logs as b,Logs as c
where a.Num = b.num and b.Num = c.Num and a.Id + 1 = b.Id and b.Id + 1 = c.Id