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) | Date(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 | +----+
這道題給了我們一個Weather表,讓我們找出比前一天溫度高的Id,由於Id的排列未必是按順序的,所以我們要找前一天就得根據日期來找,我們可以使用MySQL的函數Datadiff來計算兩個日期的差值,我們的限制條件是溫度高且日期差1,參見代碼如下:
解法一:
SELECT w1.Id FROM Weather w1, Weather w2 WHERE w1.Temperature > w2.Temperature AND DATEDIFF(w1.Date, w2.Date) = 1;
下面這種解法我們使用了MySQL的TO_DAYS函數,用來將日期換算成天數,其余跟上面相同:
解法二:
SELECT w1.Id FROM Weather w1, Weather w2 WHERE w1.Temperature > w2.Temperature AND TO_DAYS(w1.Date) = TO_DAYS(w2.Date) + 1;
我們也可以使用Subdate函數,來實現日期減1,參見代碼如下:
解法三:
SELECT w1.Id FROM Weather w1, Weather w2 WHERE w1.Temperature > w2.Temperature AND SUBDATE(w1.Date, 1) = w2.Date;
最后來一種完全不一樣的解法,使用了兩個變量pre_t和pre_d分別表示上一個溫度和上一個日期,然后當前溫度要大於上一溫度,且日期差為1,滿足上述兩條件的話選出來為Id,否則為NULL,然后更新pre_t和pre_d為當前的值,最后選出的Id不為空即可:
解法四:
SELECT Id FROM ( SELECT CASE WHEN Temperature > @pre_t AND DATEDIFF(Date, @pre_d) = 1 THEN Id ELSE NULL END AS Id, @pre_t := Temperature, @pre_d := Date FROM Weather, (SELECT @pre_t := NULL, @pre_d := NULL) AS init ORDER BY Date ASC ) id WHERE Id IS NOT NULL;
參考資料:
https://leetcode.com/discuss/33641/two-solutions
https://leetcode.com/discuss/52370/my-simple-solution-using-inner-join
https://leetcode.com/discuss/86435/a-simple-straightforward-solution-and-its-very-fast
