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 |
+----+

解題思路:

自己連接自己,條件是連接自己昨天的行。

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;

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章