题目描述

(通过次数458 | 提交次数628,通过率72.93%)

表: Weather
+-------------+------+
| Column Name | Type |
+-------------+------+
| city_id     | int  |
| day         | date |
| degree      | int  |
+-------------+------+
(city_id, day) 是该表的主键。
该表中的每一行都包含某一天某个城市的天气程度。
所有的温度都是在 2022 年。

编写一个 SQL 来查询每个城市中有最高温度记录的日子。如果同一城市多次记录最高气温,则返回其中最早的一天。
返回按 city_id 升序排序的结果表。

查询结果格式示例如下。
示例 1:
输入: 
Weather 表:
+---------+------------+--------+
| city_id | day        | degree |
+---------+------------+--------+
| 1       | 2022-01-07 | -12    |
| 1       | 2022-03-07 | 5      |
| 1       | 2022-07-07 | 24     |
| 2       | 2022-08-07 | 37     |
| 2       | 2022-08-17 | 37     |
| 3       | 2022-02-07 | -7     |
| 3       | 2022-12-07 | -6     |
+---------+------------+--------+
输出: 
+---------+------------+--------+
| city_id | day        | degree |
+---------+------------+--------+
| 1       | 2022-07-07 | 24     |
| 2       | 2022-08-07 | 37     |
| 3       | 2022-12-07 | -6     |
+---------+------------+--------+
解释: 
城市 1 的最高气温出现在 2022-07-07,为24度。
城市 2 的最高气温出现在 2022-08-07 和 2022-08-17,为37度。我们选择较早的日期 (2022-08-07)。
城市 3 的最高气温记录在 2022-12-07 年,为-6 度。

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/the-first-day-of-the-maximum-recorded-degree-in-each-city

//测试数据
Create table If Not Exists Weather (city_id int, day date, degree int);

insert into Weather (city_id, day, degree) values ('1', '2022-01-07', '-12');
insert into Weather (city_id, day, degree) values ('1', '2022-03-07', '5');
insert into Weather (city_id, day, degree) values ('1', '2022-07-07', '24');
insert into Weather (city_id, day, degree) values ('2', '2022-08-07', '37');
insert into Weather (city_id, day, degree) values ('2', '2022-08-17', '37');
insert into Weather (city_id, day, degree) values ('3', '2022-02-07', '-7');
insert into Weather (city_id, day, degree) values ('3', '2022-12-07', '-6');

解题思路

Genders表保存了用户的性别。
Weather表保存了每一天每个城市的温度。
题目要求:查询出每个城市温度最高的那一天。
这是典型的开窗分组排名,然后取第一名的场景。可以使用row_number+partition by对city_id分组,然后使用温度和city_id排序,最后取出每个城市排名第一的记录。

参考SQL

未特别说明的情况下,参考SQL为基于MySQL8.0实现。
select
    a.city_id,
    a.day,
    a.degree
from (
    select
        city_id,
        day,
        degree,
        row_number() over(partition by city_id order by degree desc,day) rn
    from Weather
)a
where a.rn = 1
order by a.city_id;

picture loss