197 Rising Temperature
To determine if tomorrow’s temperature is higher than today’s, we can use the special date function DATE_ADD(). The key idea is to self-join the Weather table in a way that ensures we only retain rows where both dates exist.
Approach
- Use a self-join:
- We join
Weatherwith itself on the condition thatw1.recordDateis exactly one day ahead ofw2.recordDate:
FROM Weather AS w1 JOIN Weather AS w2 ON w1.recordDate = DATE_ADD(w2.recordDate, INTERVAL 1 DAY)- This ensures that for each date in
w1, there exists a corresponding previous day inw2, keeping only consecutive date pairs.
- We join
- Filter out cases where tomorrow’s temperature is higher:
- We apply a
WHEREcondition to select records where the next day’s temperature is greater than the current day’s:
WHERE w1.temperature > w2.temperature - We apply a
Conclusion
By structuring the query this way, we can efficiently find days where the temperature increased compared to the previous day. If this logic is unclear, try manually constructing a small table to visualize the self-join and see how only rows where both dates exist are retained.
