LeetCode:197.上升的温度
题目
给定一个 Weather
表,编写一个 SQL 查询,来查找与之前(昨天的)日期相比温度更高的所有日期的 Id。
+---------+------------------+------------------+
| Id(INT) | RecordDate(DATE) | Temperature(INT) |
+---------+------------------+------------------+
| 1 | 2015-01-01 | 10 |
| 2 | 2015-01-02 | 25 |
| 3 | 2015-01-03 | 20 |
| 4 | 2015-01-04 | 30 |
+---------+------------------+------------------+
例如,根据上述给定的 Weather 表格,返回如下 Id:
+----+
| Id |
+----+
| 2 |
| 4 |
+----+
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/rising-temperature
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解答
第一感觉,用 oracle
中的分析函数,偏移函数 lag
、lead
,不过不知道这里支不支持窗口函数,测试一番再说。
---- oracle ----
/* Write your PL/SQL query statement below */
select Id
from
(
select Id,
RecordDate,
Temperature,
lag(Temperature,1) over(order by RecordDate) as Temperature_2
from Weather
)
where Temperature > Temperature_2;
测试用例不通过,因为有一个测试用例是中间间隔了1天,并非前后2天,所以这道题不能通过偏移函数来进行求解,还是得通过前后2天进行连接,如果找不到对应的时间差则关联不上,这样的答案才是正确的。
在 MySQL
环境中,使用 join
和 datediff
函数进行求解。
---- MySQL ----
select a.Id as Id
from Weather a
left join Weather b
on datediff(a.RecordDate, b.RecordDate) = 1
where a.Temperature > b.Temperature; ---- 274ms
-- 第一次提交的时候把最后温度的过滤条件写成了and,怪不得提交不通过,改为where之后便可以了。
---- MySQL ----
# Write your MySQL query statement below
select a.Id
from Weather a,
Weather b
where a.Temperature > b.Temperature
and datediff(a.RecordDate, b.RecordDate) = 1; ---- 275ms
这样子就通过?得好好考虑一下。。
---- oracle ----
/* Write your PL/SQL query statement below */
select a.Id as Id
from Weather a
left join Weather b
on a.RecordDate = b.RecordDate - 1
where a.Temperature > b.Temperature;
---- 没通过
其实本身,这样子的解法是没有问题的,只是测试样例中的数据不够规范,所以测试才不通过。
另外,果然看到一种通过偏移函数解答的,再进行尝试一番,修改一下。
---- oracle ----
/* Write your PL/SQL query statement below */
select t.Id as Id
from
(
select Id,
RecordDate,
Temperature,
lag(Temperature,1) over(order by RecordDate) as Temperature_2,
lag(RecordDate,1) over(order by RecordDate) as RecordDate_2
from Weather
) t
where t.Temperature > t.Temperature_2
and round(to_number(t.RecordDate - t.RecordDate_2)) = 1; ---- 537ms
证明,偏移函数还可以可以的!!!
思考
复习一下 MySQL
的 datediff
函数。
第一个参数减掉第二个参数。
datediff('2007-12-31','2007-12-30'); # 1
datediff('2010-12-30','2010-12-31'); # -1
另外,也可以通过 date_add
函数进行时间加减。
date_add('2019-10-26', interval 1 day)
使用 oracle
中的偏移函数进行求解。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)