Rising Temperature
阿新 • • 發佈:2018-12-31
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 | +----+
解題思路:
自己連線自己,條件是連線自己昨天的行。
TO_DAYS函式 返回一個天數! 啊哈?什麼天數? 從年份0開始的天數
比如:
mysql> SELECT TO_DAYS(‘1997-10-07′);
結果 729669
就是從0年開始 到1997年10月7號之間的天數
理解這個之後那麼一切就變得拉麼簡單!有一張表!lito表 有一個欄位 create_time 型別 datetime
如果要查詢當前表中昨天的資料那麼
select * from lito where to_days(now())-to_days(create_time)<1
select w.Id from Weather as w
join Weather as preW on TO_DAYS(w.RecordDate)=1+TO_DAYS(preW.RecordDate)
where w.Temperature > preW.Temperature;