0
点赞
收藏
分享

微信扫一扫

数据库:上升的温度

中间件小哥 2022-05-05 阅读 77
sql

题目链接:https://leetcode-cn.com/problems/rising-temperature/

# Write your MySQL query statement below
#输入:
#Weather 表:
#+----+------------+-------------+
#| id | recordDate | Temperature |
#+----+------------+-------------+
#| 1  | 2015-01-01 | 10          |
#| 2  | 2015-01-02 | 25          |
#| 3  | 2015-01-03 | 20          |
#| 4  | 2015-01-04 | 30          |
#+----+------------+-------------+
#输出:
#+----+
#| id |
#+----+
#| 2  |
#| 4  |
#+----+
#解释:
#2015-01-02 的温度比前一天高(10 -> 25)
#2015-01-04 的温度比前一天高(20 -> 30)

#way1
select a.Id from  
Weather as a join Weather as b 
on a.Temperature > b.Temperature 
and dateDiff(a.RecordDate,b.RecordDate) = 1

#way2
select b.id
from weather a join weather b
on b.recordDate = date_add(a.recordDate, interval 1 day) 
    and b.temperature > a.temperature

#dateDiff返回两个参数之间间隔的天数
#为了方便比较,上述进行了自连接

#下面是补充知识点:
#返回值是相差的天数
DATEDIFF('2007-12-31','2007-12-30');#1
DATEDIFF('2010-12-30','2010-12-31');#-1
#计算相差天数:
select TIMESTAMPDIFF(DAY,'2019-05-20', '2019-05-21'); # 1
#计算相差小时数:
select TIMESTAMPDIFF(HOUR, '2015-03-22 07:00:00', '2015-03-22 18:00:00'); # 11
#计算相差秒数:
select TIMESTAMPDIFF(SECOND, '2015-03-22 07:00:00', '2015-03-22 7:01:01'); # 61
#interval
"2015-01-03"+interval'1' day #2015-01-04
#从日期减去指定的时间间隔
DATE_SUB("2008-12-29",INTERVAL 2 DAY) 
#从日期加上指定的时间间隔
adddate("2015-01-03",INTERVAL 1 day) #2015-01-04
#返回从0000到现在的天数
to_days("2015-01-04")


举报

相关推荐

0 条评论