心得
題目要求找出溫度比前一天高的資料,這裡用了DATE_SUB
與TO_DAYS
兩種方式來解答。
題目
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 | +----+
答案
Sub Query
# Write your MySQL query statement below SELECT a.Id FROM Weather AS a WHERE ( SELECT z.Temperature FROM Weather AS z WHERE DATE_SUB(a.Date, INTERVAL 1 DAY) = z.Date) < a.Temperature
Join
# Write your MySQL query statement below SELECT a.Id FROM Weather AS a JOIN Weather AS b ON DATE_SUB(a.Date, INTERVAL 1 DAY) = b.Date WHERE a.Temperature > b.Temperature
TO_DAYS
# Write your MySQL query statement below SELECT a.Id FROM Weather AS a JOIN Weather AS b ON TO_DAYS(a.Date) - TO_DAYS(b.Date) = 1 WHERE a.Temperature > b.Temperature
參考: