【LeetCode-SQL】197. 上升的温度

这篇博客探讨了如何使用SQL查询找出与前一天相比温度升高的日期。通过两种方法,包括inner join和cross join,结合时间处理和逻辑思维,解决LeetCode上的相关问题。文章提供了具体的SQL代码示例,并提到了在实际业务中的应用和相关函数的使用。

一、题目

表 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 -> 252015-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:
1
时间差计算:
2

代码:

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()函数的使用?

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值