Add SQL query for rising temperature comparison #1
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
PR Title Format: 197.Rising Temperature.sql
💡 Intuition
The goal is to find records where the temperature today is higher than the temperature yesterday. This inherently requires comparing two different rows from the same Weather table. The key is to correctly link 'today's' record with 'yesterday's' record, which can be done based on the recordDate where today's date is exactly one day after yesterday's date.
✍️ Approach
Self-Join: Join the Weather table with itself (a self-join) to compare different rows. I'll use aliases: today for the current day's record and yesterday for the previous day's record.
Date Comparison: The join condition must ensure that yesterday.recordDate is one day before today.recordDate. The DATEDIFF(today.recordDate, yesterday.recordDate) = 1 function/expression precisely achieves this, as it calculates the difference in days between the two dates.
Temperature Comparison: Apply a WHERE clause to filter the joined records, keeping only those where today.temperature is greater than yesterday.temperature.
Selection: Finally, select the id from the today alias, as the problem asks for the ID of the day with the higher temperature.
Code Solution (SQL)
SQL
SELECT today.id
FROM Weather yesterday
CROSS JOIN Weather today -- Using JOIN here is more standard, but CROSS JOIN works as the condition is in WHERE.
WHERE DATEDIFF(today.recordDate, yesterday.recordDate) = 1
AND today.temperature > yesterday.temperature
;
🔗 Related Issues
By submitting this PR, I confirm that:
[x] This is my original work not totally AI generated
[x] I have tested the solution thoroughly on leetcode
[x] I have maintained proper PR description format
[x] This is a meaningful contribution, not spam