Hello everyone, I am Kongkong star. This article will take you to understand a simple sql practice question.
Article directory
foreword
1. Topic: 197. Rising temperature
Table: Weather
+---------------+---------+
| Column Name | Type |
+---------------+---------+
| id | int |
| recordDate | date |
| temperature | int |
+---------------+---------+
id is the primary key of this table
which contains temperature information for a specific date
Write a SQL query to find the id's of all dates with a higher temperature than the previous (yesterday's) date.
The returned results do not require order.
The query result format is as follows.
输入:
Weather 表:
+----+------------+-------------+
| id | recordDate | Temperature |
+----+------------+-------------+
| 1 | 2015-01-01 | 10 |
| 2 | 2015-01-02 | 25 |
| 3 | 2015-01-03 | 20 |
| 4 | 2015-01-04 | 30 |
+----+------------+-------------+
输出:
+----+
| id |
+----+
| 2 |
| 4 |
+----+
Explanation:
The temperature on 2015-01-02 was higher than the previous day (10 -> 25)
The temperature on 2015-01-04 was higher than the previous day (20 -> 30)
Two, problem solving
1. Correct demonstration①
Submit SQL
select u2.id from Weather u1
left join Weather u2
on DATE_ADD(u1.recordDate,INTERVAL 1 DAY)=u2.recordDate
where u2.Temperature>u1.Temperature;
operation result
2. Correct demonstration②
Submit SQL
select u2.id from Weather u1,Weather u2
where DATE_SUB(u2.recordDate,INTERVAL 1 DAY)=u1.recordDate
and u2.Temperature>u1.Temperature;
operation result
3. Demonstrate correctly③
Submit SQL
select id from Weather u1
where exists (
select 1 from Weather u2
where DATE_ADD(u2.recordDate,INTERVAL 1 DAY)=u1.recordDate
and u1.Temperature>u2.Temperature
)
operation result
4. Correct demonstration④
Submit SQL
select u2.id from Weather u1
join Weather u2
on DATEDIFF(u2.recordDate,u1.recordDate)=1
where u2.Temperature>u1.Temperature;
operation result
5. Other
Summarize
DATE_ADD
The (date,INTERVAL expr type) function returns the date with the INTERVAL time interval added to date.
DATE_SUB
The (date,INTERVAL expr type) function returns the date with the INTERVAL time interval subtracted from date.
DATEDIFF
The (date1,date2) function calculates the number of days between two dates.