essay

hot50-上升的温度

#mysql

hot50——上升的温度

表: Weather

Column Name Type
id int
recordDate date
temperature int

id 是该表具有唯一值的列。
没有具有相同 recordDate 的不同行。
该表包含特定日期的温度信息

编写解决方案,找出与之前(昨天的)日期相比温度更高的所有日期的 id 。

返回结果 无顺序要求 。

结果格式如下例子所示。

示例 1:

输入:
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)

答:

select today.id from Weather as today 
join Weather as yesterday 
on datediff(today.recordDate, yesterday.recordDate) = 1
where today.Temperature > yesterday.Temperature

这道题的核心是如何把"今天"和"昨天"关联起来。
方法:自连接(Self Join)
把 Weather 表想象成两张表:

  • today 表:代表今天的记录
  • yesterday 表:代表昨天的记录

然后通过 日期差 = 1 把两张表关联起来。
today.recordDate - yesterday.recordDate = 1
用到的函数:DATEDIFF(date1, date2)

计算两个日期相差的天数:

DATEDIFF('2015-01-02', '2015-01-01')  -- 结果: 1
comments如果有不同意见或者补充,直接留在这里。
contact

在别处继续找到我

如果你想聊技术、设计,或者只是打个招呼。

暂未配置外部链接