一、题目
表 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)
二、解决
1、inner join
思路: 略。
代码-版本1:
select t2.id
from weather t1
inner join weather t2
on t2.recorddate = adddate(t1.recorddate, interval 1 day)
# on datediff(t2.recordDate, t1.recordDate) = 1
# on timestampdiff(day, t1.recordDate, t2.recordDate) = 1 # t2.recordDate-t1.recordDate=1, 较慢
# on to_days(t2.recordDate) - to_days(t1.recordDate) = 1 # 较慢
where t2.temperature > t1.temperature; # and t2.temperature > t1.temperature; # 也可以
2、cross join
思路:
考点:
- 1)多表联结。
- 2)不同数据格式。
- 3)时间处理。在业务中经常用到,要熟练掌握。
- 4)逻辑思维。用课程《分析方法》中的逻辑树分析方法,将复杂问题拆解成一个个可解决的子
coss join:

时间差计算:

代码:
select t2.id
from weather as t1
cross join weather as t2
on datediff(t2.recordDate, t1.recordDate) = 1
where t2.temperature > t1.temperature;
三、参考
1、adddate()函数 方法 亲测更快
2、上升的温度
3、图解SQL面试题:如何比较日期数据?
4、mysql中date_add()函数的使用?
这篇博客探讨了如何使用SQL查询找出与前一天相比温度升高的日期。通过两种方法,包括inner join和cross join,结合时间处理和逻辑思维,解决LeetCode上的相关问题。文章提供了具体的SQL代码示例,并提到了在实际业务中的应用和相关函数的使用。
462

被折叠的 条评论
为什么被折叠?



