[LeetCode] 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) | 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的排列未必是按順序的,所以我們要找前一天就得根據(jù)日期來找,我們可以使用MySQL的函數(shù)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函數(shù),用來將日期換算成天數(shù),其余跟上面相同:
解法二:
SELECT w1.Id FROM Weather w1, Weather w2
WHERE w1.Temperature > w2.Temperature AND TO_DAYS(w1.Date) = TO_DAYS(w2.Date) + 1;
我們也可以使用Subdate函數(shù),來實現(xiàn)日期減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
到此這篇關于SQL實現(xiàn)LeetCode(197.上升溫度)的文章就介紹到這了,更多相關SQL實現(xiàn)上升溫度內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
您可能感興趣的文章:- SQL實現(xiàn)LeetCode(196.刪除重復郵箱)
- SQL實現(xiàn)LeetCode(185.系里前三高薪水)
- SQL實現(xiàn)LeetCode(184.系里最高薪水)
- SQL實現(xiàn)LeetCode(183.從未下單訂購的顧客)
- SQL實現(xiàn)LeetCode(182.重復的郵箱)
- SQL實現(xiàn)LeetCode(181.員工掙得比經(jīng)理多)
- SQL實現(xiàn)LeetCode(180.連續(xù)的數(shù)字)
- C++實現(xiàn)LeetCode(179.最大組合數(shù))