MYSQL實現"上升的溫度"的方法
阿新 • • 發佈:2018-12-10
給定一個Weather表,寫一條SQL語句返回所有溫度比前一天高的資料的Id
+---------+------------------+------------------+ | 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 | +---------+------------------+------------------+
例如,上面的天氣表返回下面的Id結果
+----+ | Id | +----+ | 2 | | 4 | +----+
DATEDIFF() 函式返回兩個日期之間的天數。
由於Id的排列未必是按順序的,所以要找前一天就得根據日期來找,可以使用MySQL的函式Datadiff來計算兩個日期的差值。限制條件是溫度高且日期差1
SELECT W1.Id FROM Weather AS W1, Weather AS W2 WHERE DATEDIFF(W1.RecordDate, W2.RecordDate)=1 AND W1.Temperature>W2.Temperature
2:利用DATA_SUB()方法
DATE_SUB() 函式從日期減去指定的時間間隔
SELECT W1.Id
FROM Weather AS W1, Weather AS W2
WHERE DATE_SUB(W1.RecordDate, INTERVAL 1 DAY)=W2.RecordDate AND W1.Temperature>W2.Temperature
3:利用DATA_ADD()方法
SELECT W1.Id FROM Weather AS W1, Weather AS W2 WHERE W1.RecordDate=DATE_ADD(W2.RecordDate, INTERVAL 1 DAY) AND W1.Temperature>W2.Temperature
to_days(date) -將日期型別轉為數字型別
from_days(date)-將天數轉為日期
SELECT W1.Id
FROM Weather AS W1, Weather AS W2
WHERE TO_DAYS(W1.RecordDate)-TO_DAYS(W2.RecordDate)=1 AND W1.Temperature>W2.Temperature