加载中...
197-上升的温度(Rising Temperature)
发表于:2021-12-03 | 分类: 简单
字数统计: 408 | 阅读时长: 2分钟 | 阅读量:

原文链接: https://leetcode-cn.com/problems/rising-temperature

英文原文

Table: Weather

+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| id            | int     |
| recordDate    | date    |
| temperature   | int     |
+---------------+---------+
id is the primary key for this table.
This table contains information about the temperature on a certain day.

 

Write an SQL query to find all dates' Id with higher temperatures compared to its previous dates (yesterday).

Return the result table in any order.

The query result format is in the following example.

 

Example 1:

Input: 
Weather table:
+----+------------+-------------+
| id | recordDate | temperature |
+----+------------+-------------+
| 1  | 2015-01-01 | 10          |
| 2  | 2015-01-02 | 25          |
| 3  | 2015-01-03 | 20          |
| 4  | 2015-01-04 | 30          |
+----+------------+-------------+
Output: 
+----+
| id |
+----+
| 2  |
| 4  |
+----+
Explanation: 
In 2015-01-02, the temperature was higher than the previous day (10 -> 25).
In 2015-01-04, the temperature was higher than the previous day (20 -> 30).

中文题目

Weather

+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| id            | int     |
| recordDate    | date    |
| temperature   | int     |
+---------------+---------+
id 是这个表的主键
该表包含特定日期的温度信息

 

编写一个 SQL 查询,来查找与之前(昨天的)日期相比温度更高的所有日期的 id

返回结果 不要求顺序

查询结果格式如下例:

Weather
+----+------------+-------------+
| id | recordDate | Temperature |
+----+------------+-------------+
| 1  | 2015-01-01 | 10          |
| 2  | 2015-01-02 | 25          |
| 3  | 2015-01-03 | 20          |
| 4  | 2015-01-04 | 30          |
+----+------------+-------------+

Result table:
+----+
| id |
+----+
| 2  |
| 4  |
+----+
2015-01-02 的温度比前一天高(10 -> 25)
2015-01-04 的温度比前一天高(20 -> 30)

通过代码

官方题解

方法:使用 JOINDATEDIFF() 子句

算法

MySQL 使用 DATEDIFF 来比较两个日期类型的值。

因此,我们可以通过将 weather 与自身相结合,并使用 DATEDIFF() 函数。

[]
SELECT weather.id AS 'Id' FROM weather JOIN weather w ON DATEDIFF(weather.date, w.date) = 1 AND weather.Temperature > w.Temperature ;

统计信息

通过次数 提交次数 AC比率
100736 188818 53.4%

提交历史

提交时间 提交结果 执行时间 内存消耗 语言
上一篇:
196-删除重复的电子邮箱(Delete Duplicate Emails)
下一篇:
198-打家劫舍(House Robber)
本文目录
本文目录