the leetcode question 197.Rising Temperature
Given a Weather table, write a SQL query to find all dates’ Ids with higher temperature compared to its previous (yesterday’s) dates.
+---------+------------------+------------------+ | 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 | +---------+------------------+------------------+ For example, return the following Ids for the above Weather table: +----+ | Id | +----+ | 2 | | 4 | +----+
i didn’t know the function DATEDIFF()
,so i wrote my sql solution:
select w1.Id from Weather w1,Weather w2 where w1.RecordDate - w2.RecordDate = 1 and w1.Temperature > w2.Temperature
and i went through the testcase but got a wrong submit,the right solution is use funtion DATEDIFF()
select w1.Id from Weather w1,Weather w2 where DATEDIFF(w1.RecordDate,w2.RecordDate)=1 and w1.Temperature > w2.Temperature
so my question is what’s the difference between
DATEDIFF(w1.RecordDate,w2.RecordDate)=1
and w1.RecordDate - w2.RecordDate = 1
thank you for your help
Advertisement
Answer
If the datatype of RecordDate
is DATETIME
rather than DATE
, subtracting them returns a large value that contains the difference between the times as well as the dates. E.g.
mysql> select cast('2019-03-21 10:20:30' as datetime) - cast('2019-03-11 9:15:20' as datetime) as difference; +-----------------+ | difference | +-----------------+ | 10010510.000000 | +-----------------+
But if they’re DATE
then subtraction should be the same as DATEDIFF()
:
mysql> select cast('2019-03-21' as date) - cast('2019-03-11' as date) as difference; +------------+ | difference | +------------+ | 10 | +------------+